[LeetCode]160.Intersection of Two Linked Lists
阿新 • • 發佈:2017-05-04
col style return tro nod sts diff original you
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.
可以將A,B兩個鏈表看做兩部分,交叉前與交叉後。例子中
交叉前A: a1 → a2
交叉前B: b1 → b2 → b3
交叉後AB一樣: c1 → c2 → c3
所以 ,交叉後的長度是一樣,所以,交叉前的長度差即為總長度差。
只要去除長度差,距離交叉點就等距了。
1 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 2 if(headA == null || headB == null) return null; 3 ListNode tempA = headA;//計算鏈表長度用 4 ListNode tempB = headB; 5 int len_A = 1; 6 int len_B = 1; 7 while (tempA.next != null) {tempA = tempA.next; len_A++;}// 計算鏈表長度 8 while (tempB.next != null) {tempB = tempB.next; len_B++;} 9 int diff ;//長度差 10 //去除長度差 11 if(len_A > len_B){ 12 diff = len_A - len_B; 13 while(diff > 0){ 14 headA = headA.next; 15 diff--; 16 } 17 } 18 else if (len_A < len_B){ 19 diff = len_B - len_A; 20 while(diff > 0){ 21 headB = headB.next; 22 diff--; 23 } 24 } 25 while(headA != headB){ 26 headA = headA.next; 27 headB = headB.next; 28 } 29 return headA; 30 }
參考:
http://www.cnblogs.com/ganganloveu/p/4128905.html
[LeetCode]160.Intersection of Two Linked Lists