[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

所以 ,交叉后的长度是一样,所以,交叉前的长度差即为总长度差。

只要去除长度差,距离交叉点就等距了。

 public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA=0 ,lenB=0;
int dis;
for(ListNode x = headA;x != null;x = x.next) lenA++; //len of a
for(ListNode x = headB;x != null;x = x.next) lenB++;// len of b
dis = lenB - lenA;//distence of a and b if(dis > 0)//b is longer than a move headb
for(int i = dis;i > 0;i --) headB = headB.next;
else // a is longer than b move heada
for(int i = -dis;i > 0;i --) headA = headA.next; while(headA != headB){ // heada and headb are equal?
headA = headA.next;
headB = headB.next;
}
return headA;
}

参考:

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

上一篇:DevExpress v18.2新版亮点——Reporting篇(二)


下一篇:Java for LeetCode 160 Intersection of Two Linked Lists