Leetcode 160. Intersection of Two Linked Lists
来源:互联网 发布:tensorflow ocr 编辑:程序博客网 时间:2024/06/10 01:24
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.
s思路:
1. 这道题确实做过,印象深刻。通过做辅助线,把问题转换成熟悉的问题,再用熟悉的配方来解决。假设有两条链表A,B,我们先遍历A到A的结尾然后把A的尾巴指向A的头部,这样一来,就有一个cycle,如果我们再从B开始用快慢指针大法去检测这个cycle,并找到cycle所在的地方,就是两条链表的intersection 开始的地方。如果AB没有intersection,那么我们遍历B就不会遇到cycle。
class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(!headA||!headB) return NULL; ListNode* pa=headA,*pb=headB; //step 1:A首尾相连成闭环 while(pa&&pa->next){ pa=pa->next; } pa->next=headA; //step 2:快慢指针检测是否cycle ListNode* fast=headB->next,*slow=headB; while(fast&&fast!=slow){ fast=fast->next?fast->next->next:NULL; slow=slow->next; } if(fast) { fast=headB; slow=slow->next; //step 3: 定位cycle起始 while(fast!=slow){ fast=fast->next; slow=slow->next; } } //step4: 断开刚才引入的cycle pa->next=NULL; return fast; }};
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
- [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
- 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
- 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
- leetcode 160. Intersection of Two Linked Lists
- 160.[Leetcode]Intersection of Two Linked Lists
- 2016 机器学习之路:一年从无到有掌握机器学习
- UEFI+GPT hard disk install multi linux system
- 小飞鱼通达.商务网络平台-OA二次开发程序基础网络直播课程
- 测试常用规则
- javascript:void(0)
- Leetcode 160. Intersection of Two Linked Lists
- 迷你 DVD管理器
- React 入门实例教程
- mysql性能优化-配置参数优化
- java学习笔记-excel表格形式记录
- 机器学习算法比较
- Redis 应用案例 - 在问题中不断成长
- 【UVA11542】Square(高斯消元)
- 创业案例:如何调整股权,才不伤害合伙人感情?