Intersection of Two Linked Lists

来源:互联网 发布:opera 10.10 linux 编辑:程序博客网 时间:2024/05/12 20:07
/* Write a program to find the node at which* the intersection of two singly linked lists begins.* This solution runs O(n) time.** Basic idea:* 1. Traverse the two linked list to find length M and N;* 2. Get back to the heads, the skip |M - N| nodes on the longer list;* 3. Now walk through both lists together until you find the common node.** Important notes:* When submitting to leetcode, the debug info* System.out.println() should be commented,* since it is very time consuming!*/ public class Solution {public ListNode getIntersectionNode(ListNodeheadA, ListNode headB) { /* My answer starts here */ListNode ptrA= headA;ListNode ptrB= headB;int lengthA= 0;int lengthB= 0;int i; // get the length of list Awhile (null!= ptrA) {//System.out.println("ptrA: " + ptrA.val);lengthA++;ptrA = ptrA.next;}ptrA = headA;// pointer back to the head // get the length of list Bwhile (null!= ptrB) {//System.out.println("ptrB: " + ptrB.val);lengthB++;ptrB = ptrB.next;}ptrB = headB;// pointer back to the head // skip the first |M - N| nodes of the longer listif (lengthA>= lengthB) {for (i = 0; i < lengthA - lengthB; i++) {ptrA = ptrA.next;}} else {for (i = 0; i < lengthB - lengthA; i++) {ptrB = ptrB.next;}} // compare one by one of the remaining nodeswhile (null!= ptrA) {if (ptrA.val== ptrB.val) {return ptrA;// find the intersection}ptrA = ptrA.next;ptrB = ptrB.next;}return null; // no intersection /* My answer ends here */}}
0 0
原创粉丝点击