题目:160. 相交链表
思路:双指针。
对于两条链表a,b,a+b的节点数等于b+a的节点数。
所以,我们用两个指针分别指向两个链表,遍历他们。如果a指针到了a链表最后一个节点,那么把a指针指向b链表;对b链表和b指针也是如此。
- 如果两个链表有交点,那么上述遍历方式两个指针会同时到达起始交点;
- 如果两个链表没有交点,那么当两个指针会同时到达对方的末节点。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
while (a != null && b != null) {
if (a == b) {
return a;
}
if (a.next == null && b.next == null) {
return null;
}
if (a.next == null) {
a = headB;
}
else {
a = a.next;
}
if (b.next == null) {
b = headA;
}
else {
b = b.next;
}
}
return null;
}
}