[LeetCode]160.Intersection of Two Linked Lists(2个链表的公共节点)

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 class Solution {
 2     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 3         int lenA=0 ,lenB=0;
 4         int dis;
 5         for(ListNode x = headA;x != null;x = x.next) lenA++; //len of a
 6         for(ListNode x = headB;x != null;x = x.next) lenB++;// len of b
 7         dis = lenB - lenA;//distence of a and b
 8     
 9         if(dis > 0)//b is longer than a  move headb 
10             for(int i = dis;i > 0;i --) headB = headB.next;
11         else  // a is longer than b move heada
12             for(int i = -dis;i > 0;i --) headA = headA.next;
13         
14         while(headA != headB){ // heada and headb are equal?
15             headA = headA.next;
16             headB = headB.next;
17         }
18         return headA;
19     }

 

参考:

http://www.cnblogs.com/ganganloveu/p/4128905.html

posted @ 2017-05-04 00:18  乐乐章  阅读(189)  评论(0编辑  收藏  举报