160. Intersection of Two Linked Lists
来源:互联网 发布:windows编程循序渐进 编辑:程序博客网 时间:2024/05/24 05:02
1.Question
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.
/** * 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 && headB) { int m = getListLength(headA); int n = getListLength(headB); if(m < n) {ListNode* temp = headA; headA = headB; headB = temp;} int s = abs(m - n); while(s-- > 0) headA = headA->next; while(headA) { if(headA == headB) return headA; else {headA = headA->next; headB = headB->next;} } } return NULL; } int getListLength(ListNode *node) { int n = 0; while(node) {n++; node = node->next;} return n; }};
3.Note
a. 解题思路是,如果A和B的长度相同,而且有重合部分,那么A和B的重叠部分的各自对应位置是一样的,我们只需要比较对应位置上是否重叠就行了。那么,我们只要把A和B的长度变得相同就可以了。
0 0
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- firstObject 和 [0]的区别-iOS初学
- Closeable
- Spring4集成quartz,Maven打包为可执行jar或者war
- WKWebView的详细使用
- 1002 Strange fuction
- 160. Intersection of Two Linked Lists
- java语言实现网络爬虫
- Intent传递对象
- Java集合对象排序测试
- c# BC证书生成
- React + ES6环境搭建与第一个应用
- django缓存优化 Local-memory 缓存 Dummy缓存 解析
- VS2013 git 版本控制 团队合作
- 使用Dom4j解析XML