题目描述
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
解题思路:
1.分别计算两个链表的长度,看那个长,先走两者长度之差。然后一起走,直到走到第一个相同结点为止,返回;
2.两条相交的链表呈Y型。可以从两条链表尾部同时出发,最后一个相同的结点就是链表的第一个相同的结点。可以利用栈来实现。(但是实现上好像有点问题,每通过)
参考代码:
#include <iostream>
#include <string.h>
#include <vector>
#include <stack>
#include <queue>
#include<algorithm>
#include <string>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
};
//第一种思路
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == NULL || pHead2 == NULL)
{
return NULL;
}
int length1 = count_step(pHead1);
int length2 = count_step(pHead2);
if (length1 > length2)
{
pHead1 = walk_step( pHead1, length1 - length2);
} else{
pHead2 = walk_step( pHead2, length2 - length1);
}
while(pHead1 != NULL)
{
if (pHead1 == pHead2) return pHead1;
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
return NULL;
}
int count_step(ListNode* my_head)
{
if (my_head == NULL)
return 0;
int sum = 0;
while (my_head)
{
sum++;
my_head = my_head->next;
}
return sum;
}
ListNode* walk_step(ListNode* my_head, int step)
{
if (my_head == NULL)
return NULL;
while (step)
{
my_head = my_head->next;
step--;
}
return my_head;
}
};
//第二种思路
//class Solution {
//public:
// ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
//
// stack<ListNode*> my_pHead1;
// stack<ListNode*> my_pHead2;
//
// if (pHead1 == NULL || pHead2 == NULL)
// return NULL;
//
// while (pHead1)
// {
// my_pHead1.push(pHead1);
// pHead1 = pHead1->next;
// }
//
// while (pHead2)
// {
// my_pHead2.push(pHead2);
// pHead2 = pHead2->next;
// }
//
// ListNode* res;
//
// while (!my_pHead1.empty() && !my_pHead2.empty())
// {
// if (my_pHead1.top() == my_pHead2.top())
// {
// res = my_pHead1.top();
// cout<<res->val<<endl;
// } else{
// break;
// }
//
// my_pHead1.pop();
// my_pHead2.pop();
//
// }
// cout<<"res:"<<res->val<<endl;
// return NULL;
// }
//};
int main()
{
Solution solution;
ListNode p1;
ListNode p2;
ListNode p3;
ListNode p12;
ListNode p11;
ListNode p23;
ListNode p22;
ListNode p21;
p21 = {21,&p22};
p22 = {22,&p23};
p23 = {23,&p3};
p11 = {11,&p12};
p12 = {12,&p3};
p3 = {3,&p2};
p2 = {2,&p1};
p1 = {1,NULL};
ListNode* my_phead1 = &p21;
ListNode* my_phead2 = &p11;
solution.FindFirstCommonNode(my_phead1,my_phead2);
return 0;
}