intersection of two linked lists


Intersection of Two Linked Lists
比较有意思。
首先计算两个链表的长度,然后把长的链表head移动到和短的链表长度相同的点。
最后,两个head开始往后移动,如果出现相同, 则返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public ListNode (ListNode headA, ListNode headB) {
if (headA == null || headB == null)
return null;

int lenA = getLen(headA);
int lenB = getLen(headB);
if (lenA > lenB) {
for (int i = lenB; i < lenA; ++i) {
headA = headA.next;
}
} else {
for (int i = lenA; i < lenB; ++i)
headB = headB.next;
}
while (headA != null && headB != null) {
if (headA == headB)
return headA;
headA = headA.next;
headB = headB.next;
}
return null;
}

public int getLen(ListNode head) {
int len = 0;
while (head != null) {
len++;
head = head.next;
}
return len;
}