相交链表(简单)
2020年5月17日
题目来源:力扣
解题
今天无聊,再水一题。
若相交,链表A: a+c, 链表B : b+c。a+c+b = b+c+a ,则会在公共处c起点相遇。若不相交,a +b = b+a ,因此相遇处是NULL
突如其来的骚,闪断我的腰。
/**
* 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) {
if (headA == null || headB == null) return null;
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}