题目:
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.(时间复杂度要求O(n),空间复杂度O(1))
思路:
长的链表先多走 (len1 - len2)步,然后和短链表同步往下走,遇到的第一个相同的节点就是第一个交点。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
ListNode *qa = headA;
ListNode *qb = headB;
int lena = 0;//链表headA的长度
int lenb = 0;//链表headB的长度
while(qa)
{
lena++;
qa = qa->next;
}
while(qb)
{
lenb++;
qb = qb->next;
}
int gap = lena > lenb ? lena - lenb : lenb - lena ;
//使qa指向长链表,qb指向短链表
if(lena > lenb)
{
qa = headA;
qb = headB;
}
else
{
qa = headB;
qb = headA;
}
//qa先走gap步
for(int i = 0 ; i < gap ; i++)
{
qa = qa->next;
}
//qa和qb再同时遍历,直到遇到相等的结点或者链表结束
while(qa && qb && qa->val != qb->val)
{
qa = qa->next;
qb = qb->next;
}
return qa;
}
};