用双指针,如果两个链表可以相交,那么利用两个链表和相同的性质,找到他们相交的的节点。用两个双指针A=headA,B=headB.两个指针分别同时遍历两个链表,直到找到公共节点。
/**
* 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, B = headB;
while (A != B) {
A = A != null ? A.next : headB;
B = B != null ? B.next : headA;
}
return A;
}
}