Intersection of Two Linked Lists
1、题目
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.
2、分析
题目大意:给两个链表,找出它们交集的那个节点,要求时间复杂度O(n),空间复杂度O(1)。
有以下几种思路:
(1) 暴力破解 ,遍历链表A的所有节点,并且对于每个节点,都与链表B中的所有节点比较,退出条件是在B中找到第一个相等的节点。时间复杂度O(lengthA*lengthB),空间复杂度O(1)。
(2) 哈希表 。遍历链表A,并且将节点存储到哈希表中。接着遍历链表B,对于B中的每个节点,查找哈希表,如果在哈希表中找到了,说明是交集开始的那个节点。时间复杂度O(lengthA+lengthB),空间复杂度O(lengthA)或O(lengthB)。
(3) 双指针法 ,指针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)。双指针法的代码如下:
以上是引用网上的解题思路,而我一开始只想到了第1,2两种解法,其实第三种也比较好想,应为两条链不一样长,比较就麻烦了,但是如果两条链表同样长,那样判断就很容易了,如果把长的链减去多出的,那样就可以得到两条一样长的链,逐一比较即可。代码如下:
/**
* 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) {
if((NULL==headA)||(NULL==headB))
return NULL;
ListNode *tA=headA;
ListNode *tB=headB;
unsigned int lenA = 0,lenB = 0;
while(tA->next){//因为如果结尾不同,一定没交集,ta指向结尾便于比较
tA=tA->next;
lenA++;}
// lenA++;求出lena为长度减一,但是我们只是要求差值,所以不用求具体长度
while(tB->next){
tB=tB->next;
lenB++;}
// lenB++;
if(tA!=tB) return NULL;
tA = headA;
tB = headB;
int n;
if(lenA>lenB)
{
n = lenA-lenB;
while(n){
tA = tA->next;
n--;}
}else
{
n = lenB-lenA;
while(n){
tB = tB->next;
n--;}
}
while(tA!=tB)
{
tA=tA->next;
tB=tB->next;
}
return tA;
}
};
注意事项:
1.所有指针做参数传值都要判断是否为null
2.格式问题,每一句一行,不要偷懒
3.记住指针位置变化,对null操作一定会挂了