160. Intersection of Two Linked Lists #
题目 #
给定两个单链表的头节点headA
和headB
,找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回null
。
思路 #
代码 #
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 ptrA = headA, ptrB = headB;
while (ptrA != ptrB) {
ptrA = ptrA.next;
ptrB = ptrB.next;
if (ptrA == null && ptrB == null) return null;
else if (ptrA == null) ptrA = headB;
else if (ptrB == null) ptrB = headA;
}
return ptrA;
}
}