题目描述
编写一个程序,找到两个单链表相交的起始节点。
思路
单链表相交,即意味着从第一个相交节点开始,后面的节点都是相同的,相交的长度也是相同的。但是两个链表可能长度不同,就需要消除长度差。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class IntersectionNode {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null)
return null;
ListNode pA = headA;
ListNode pB = headB;
while(pA != pB)
{
if(pA == null)
pA = headB;
else
pA = pA.next;
if(pB == null)
pB = headA;
else
pB = pB.next;
}
return pA;
}
}