思路:双指针,先比较两个链表的长度,使双指针在同一起跑线上,然后同时向后遍历,相遇则说明有交点。
代码:
/**
* 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 p = headA;
ListNode q = headB;
int lenA = 0;
int lenB = 0;
int l = 0;
while (p != null) {
p = p.next;
lenA++;
}
while (q != null) {
q = q.next;
lenB++;
}
p = headA;
q = headB;
if (lenA > lenB) {
l = lenA - lenB;
for (int i = 0; i < l; i++) {
p= p.next;
}
}
if (lenA < lenB) {
l = lenB - lenA;
for (int i = 0; i < l; i++) {
q= q.next;
}
}
while (p != null && q != null) {
if (p == q) {
return p;
}
p = p.next;
q = q.next;
}
return null;
}
}
思路2:
把一个链表放到Set中,再放另一个链表,如果有节点放不进去,第一个放不进去的就是交点。
思路3:
双指针,不必要求再同一起跑线上,p指针遍历表A,q 指针遍历表B,当p遍历到A的末尾时,继续从B的表头开始遍历,q同样到B的末尾时,继续从A的表头开始遍历。若两者相遇,相遇点则为交点。注意,两个指针不再同一起跑线上,但是是同时起跑的。