面试题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)
输入两个链表,找出他们的第一个公共结点。
边界条件及异常:
有一个为空
思路:
方法一:用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; }
相关文章推荐
- 12本最具影响力的程序员书籍(上)
- 代码面试最常用的10大算法
- 程序员的数学--简单的读书笔记
- iOS 面试题 11-20
- 不只是给面试加分 -- Java WeakReference的理解与使用
- 2015年阿里、网易、中兴、华为、美团等Java研发工程师面试心得
- 一个合格的程序员应该读过哪些书
- 月薪3万的程序员都避开了哪些坑
- 程序员的最高境界:呆若木鸡
- Android 面试题目总结(2)
- 程序员能力矩阵
- 程序员如何买保险?
- 这些年,我遇到过的奇葩面试官
- 程序员的3种美德
- 程序员的最高境界:呆若木鸡
- 程序开发路上的历程(上)
- iOS 面试题 10题目
- 这十个错误让面试一败涂地!
- 面试题(一)
- 前端面试:精选经典面试题(八)