首页 > 代码库 > [LeetCode]160.Intersection of Two Linked Lists

[LeetCode]160.Intersection of Two Linked Lists

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