160. Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return
null
.The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
題目大意:
找出兩個鏈表後半部分的交匯點。
思路:
1.求出兩個鏈表的長度。
2.獲取鏈表長度差n。
3.將長的鏈表先移動到第n個節點。
4.對長鏈表和短鏈表進行比較。(同時向後移動)如果在鏈表尾之前找到相等的節點,返回該節點,如果沒找到,返回NULL。
代碼如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int listLength(ListNode *head)//用快指針求鏈表長度 { ListNode * p = head; int i = 0 ; while(p && p->next) { i++; p = p->next->next; } if(p == NULL) return 2 * i; return 2 * i + 1; } ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int lenA = listLength(headA); int lenB = listLength(headB); int maxLen = lenA > lenB ? lenA :lenB; int remain ; ListNode * la,*lb; la = headA; lb = headB; if(maxLen == lenA) { remain = lenA - lenB; while(remain--) { la = la->next; } } else { remain = lenB - lenA; while(remain--) lb = lb->next; } while(lb != NULL) { if(la != lb) { la = la->next; lb = lb->next; } else { return la; } } return NULL; } };
2016-08-13 01:08:14