Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
给两个链表,找出它们交集的那个节点,要求时间复杂度O(n),空间复杂度O(1)。
思路:
两个链表公共点,则需两条链表都存在,故当一天链表比另一条长时,需跳过较长链表前端多出的若干个节点, 长的链表开始多走 (长链表的数量 - 短链表的数量)步,然后和短链表同步往下走,遇到的第一个相同的节点就是最早的公共节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode*pa=NULL,*pb=NULL;
int l1=0,l2=0,n;
pa=headA;
while(pa){pa=pa->next;l1++;}
pb=headB;
while(pb){pb=pb->next;l2++;}
pa=headA;
pb=headB;
if(l1<l2){n=l2-l1;while(n){pb=pb->next;n--;}}
else if(l1>l2){n=l1-l2;while(n){pa=pa->next;n--;}}
while(pa!=pb){pa=pa->next;pb=pb->next;
}
return pa;
}