LeetCode Intersection of Two Linked Lists
来源:互联网 发布:aws 中国 阿里云 编辑:程序博客网 时间:2024/06/15 04:43
思路:
“移动快慢指针”的思想:先让长链表的指针(假定为A)走 lenA - lenB
的距离,再两个指针一起走,碰到相同的点就有intersection。
时间复杂度O(N),空间复杂度O(1)。
/** * 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; int lenA = 0, lenB = 0; ListNode *p1 = headA, *p2 = headB; while(p1 != NULL) { lenA++; p1 = p1->next; } while(p2 != NULL) { lenB++; p2 = p2->next; } int dis = 0; p1 = headA, p2 = headB; if(lenA >= lenB) { dis = lenA - lenB; while(dis != 0) { p1 = p1->next; dis--; } }else { dis = lenB - lenA; while(dis != 0) { p2 = p2->next; dis--; } } while(p1 != NULL && p2 != NULL) { if(p1 == p2) { return p1; }else { p1 = p1->next; p2 = p2->next; } } return NULL; }};
0 0
- [leetcode] [leetcode]Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode: Intersection of Two Linked Lists
- [Leetcode] Intersection of Two Linked Lists
- [Leetcode]Intersection of Two Linked Lists
- LeetCode:Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- [leetcode]Intersection of Two Linked Lists
- leetcode:Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- 【Leetcode】:Intersection of Two Linked Lists
- leetcode Intersection of Two Linked Lists
- [LeetCode]Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode Intersection of Two Linked Lists
- NSOperation
- memcached 实现本地tomcat session共享
- LK
- 暗黑破坏神2战网服务器架设
- sed one line
- LeetCode Intersection of Two Linked Lists
- 在JAVA中查询刚插入的记录ID 利用JDBC的getGeneratedKeys获得INSERT插入后生成的主键ID
- linux终端nohup置空
- Android中如何得知当前View中的EditText正在被编辑或改动,即如何检测EditText的焦点
- 一些杂七杂八的技巧和注意项
- python 安装 pip 安装lxml 出现错误
- 实现贴标签功能
- Eclipse新建Android项目时appcompat_v7中报valuesv-21错
- python 各种测试框架