Description:
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
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
编写程序,找出两个链表的交结点
算法思路:
双指针法,指针pa、pb分别指向链表A和B的首节点。
遍历链表A,记录其长度lengthA,遍历链表B,记录其长度lengthB。
因为两个链表的长度可能不相同,比如题目所给的case,lengthA=5,lengthB=6,则作差得到lengthB-lengthA=1,将指针pb从链表B的首节点开始走1步,
即指向了第二个节点,pa指向链表A首节点,然后它们同时走,每次都走一步,当它们相等时,就是交集的节点。
时间复杂度O(lengthA+lengthB),空间复杂度O(1)。
双指针法的代码如下:
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *pa=headA,*pb=headB;
int LengthA=0,LengthB=0,l;
while(pa)
{
pa=pa->next;
LengthA++;
}
while(pb)
{
pb=pb->next;
LengthB++;
}
if(LengthA<LengthB) //说明B链更长
{
l=LengthB-LengthA;
pa=headA;
pb=headB;
while(l) //让B指针先走比A更长长度的个数的结点
{
pb=pb->next;
l--;
}
}
else
{
l=LengthA-LengthB;
pa=headA;
pb=headB;
while(l)
{
pa=pa->next;
l--;
}
}
while(pa!=pb) //两个指针同步遍历,若相遇,相遇的结点即为交集结点
{
pa=pa->next;
pb=pb->next;
}
return pb;
}