Leetcode 142. Linked List Cycle II
来源:互联网 发布:矩阵的计算方法 编辑:程序博客网 时间:2024/06/09 17:29
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
题意:找到循环链表的循环开始位置
设置快指针一次走2步和慢指针一次走1步同时遍历链表,若快指针最后和慢指针指向同一节点,则链表存在循环,接下来寻找循环开始位置:
假设慢指针第一次走到循环开始位置时走了k步,即循环起始位置距离链表头k个节点,此时快指针已经进入循环,且比慢指针多走了k步,假设循环的长度为l,则此时快指针距离慢指针l-k步,由于快指针每次比慢指针多走一步,当两指针汇合时,慢指针从循环开始位置走了l-k步,此时距离循环开始 l-(l-k)=k步,和链表头与循环开始的长度相同,此时设置另一指针从链表头开始每次一步遍历,遇到慢指针时即走到循环开始位置,文字比较苍白,自己画个图就懂了
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { ListNode *fast = head; ListNode *slow = head; while(fast!=NULL&&fast->next!=NULL){ fast = fast->next->next; slow = slow->next; if(slow == fast) break; } if(fast==NULL||fast->next == NULL) return NULL; fast = head; while(fast!=slow){ fast = fast->next; slow = slow->next; } return slow; }};
此题的思路同样可以解决LeetCode287. Find the Duplicate Number
阅读全文
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- JavaScript实现DOM对象选择器
- OpenJudge 8469: 特殊密码锁(贪心)
- Nginx之旅:安装
- 浅谈JVM垃圾回收机制
- acm中的二进制操作(未完成)
- Leetcode 142. Linked List Cycle II
- Palindrome Partitioning问题及解法
- Android6.0动态获取权限java.io.FileNotFoundException: …Permission denied
- 留言板HTML文件
- Android应用关闭系统软键盘
- 回归分析
- jdk版本错误的解决办法
- 序列化、字节对齐、字节序(C++)
- 小白也能看懂的插件化DroidPlugin原理(二)-- 反射机制和Hook入门