您的位置:首页 > 职场人生

面试题41:两个链表的第一个公共结点

2016-01-06 15:10 621 查看
题目:

输入两个链表,找出他们的第一个公共结点。

边界条件及异常:

有一个为空

思路:

方法一:用hash表来存储一个链表的结点,然后顺序遍历另一个链表,看是否在hash表中有存储值,有则是第一次出现的结点。

时间复杂度:O(n1+n2)

空间复杂度:O(n1)

方法二:由于两个链表有公共结点的话,后面部分一定相同,所以可以从链表尾部开始访问。如何从链表尾部开始访问呢?用栈来实现。

时间复杂度:O(n1+n2)

空间复杂度:O(n1+n2)

方法三:可以先确定两个链表的长度,然后从距离链表尾部相同的位置来逐渐比较。

时间复杂度:O(n1+n2)

空间复杂度:O(1)

#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <stack>
#include <algorithm>
#include <hash_set>  //for hashtable
#include <hash_map>
#include <unordered_map>
#include <set>
#include <ctime>
using namespace std;

struct ListNode{
int key;
ListNode *next;
ListNode(int _key) :key(_key), next(NULL){}
};

int GetListLength(ListNode *head)
{
int count = 0;
while (head)
{
++count;
head = head->next;
}
return count;
}

ListNode* FindFirstCommonNode(ListNode *head1, ListNode *head2)
{
if (!head1 || !head2) return NULL;
int length1 = GetListLength(head1);
int length2 = GetListLength(head2);
if (length1 > length2)
{
for (int i = 0; i < length1 - length2; i++)
head1 = head1->next;
}
else if (length1 < length2)
{
for (int i = 0; i < length2 - length1; i++)
head2 = head2->next;
}
while (head1 != head2 && head1 && head2)
{
head1 = head1->next;
head2 = head2->next;
}
return head1;
}

int main()
{
ListNode *a1 = new ListNode(1);
ListNode *a2 = new ListNode(2);
ListNode *a3 = new ListNode(3);
ListNode *a4 = new ListNode(4);
ListNode *a5 = new ListNode(5);
ListNode *a6 = new ListNode(6);
a1->next = a4; a4->next = a5; a5->next = a6;
a2->next = a3; a3->next = a4;
ListNode *a = FindFirstCommonNode(a1, a2);
cout << a->key << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: