编写一个程序,找到两个单链表相交的起始节点。
暴力遍历
/**
* 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) {
while(headA!=NULL)
{
ListNode* temp=headB;
while(headB!=NULL)
{
if(headA==headB)
return headA;
headB=headB->next;
}
headA=headA->next;
headB=temp;
}
return NULL;
}
};
集合set法
/**
* 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(headA==NULL||headB==NULL)
return NULL;
set<ListNode*> s;
while(headA!=NULL)
{
s.insert(headA);
headA=headA->next;
}
while(headB!=NULL)
{
if(s.count(headB))
return headB;
headB=headB->next;
}
return NULL;
}
};
双指针(最优)
又是两个人的爱情故事
/**
* 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(headA==NULL||headB==NULL)
return NULL;
ListNode* you=headA;
ListNode* she=headB;
while(you!=she)//若是有缘,两人终会相遇
{
if(you==NULL)
you=headB;//当你走到终点时,开始走她走过的路
else
you=you->next;
if(she==NULL)
{
she=headA;// 当她走到终点时,开始走你走过的路
}
else
she=she->next;
}
/*
while(she)//两人若是喜欢彼此
{
//那么一路上
you=she->next;//你踩着她的影子
she=you->next;//她踩着你的影子
//携手度过生命中剩下的旅途
}*/
return node1;
}
};