Leetcode 链表 Linked List Cycle II
来源:互联网 发布:剑三初始捏脸数据 编辑:程序博客网 时间:2024/06/09 22:05
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Linked List Cycle II
Total Accepted: 20444 Total Submissions: 66195My SubmissionsGiven a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
题意:给定一个单链表,判断该链表中是否存在环,如果存在,返回环开始的节点
思路:
1.定义两个指针,快指针fast每次走两步,慢指针s每次走一次,如果它们在非尾结点处相遇,则说明存在环
2.若存在环,设环的周长为r,相遇时,慢指针走了 slow步,快指针走了 2s步,快指针在环内已经走了 n环,
则有等式 2s = s + nr 既而有 s = nr
3.在相遇的时候,另设一个每次走一步的慢指针slow2从链表开头往前走。因为 s = nr,所以两个慢指针会在环的开始点相遇
复杂度:时间O(n)
struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};ListNode *detectCycle(ListNode *head) {if(!head || !head->next) return NULL;ListNode *fast, *slow, *slow2;fast = slow = slow2 = head;while(fast && fast->next){fast = fast->next->next;slow = slow->next;if(fast == slow && fast != NULL){while(slow->next){if(slow == slow2){return slow;}slow = slow->next;slow2 = slow2->next;}}}return NULL;}
0 0
- Leetcode 链表 Linked List Cycle II
- [leetcode] 【链表】142. Linked List Cycle II
- Leetcode#142(链表)-Linked List Cycle II
- leetcode---linked-list-cycle-ii---链表
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- Notepad++不保存文件打开历史与查找替换历史的方法
- 技术面试问题汇总第002篇:猎豹移动反病毒工程师part2
- 一网打尽!200+值得收藏的设计师资源站
- android开发之继承BaseAdapter实现通用数据适配器
- LeetCode N-Queens
- Leetcode 链表 Linked List Cycle II
- codeforces 463E Caisa and Tree 栈+dfs
- C# 基类 派生类 方法隐藏 方法重写
- python小工具:批量替换某个目录下的文件名
- Linux下Apache与Tomcat整合,请求转发【实践成功记录版本】
- C++ 练习笔记
- 关于ios object-c 类别-分类 category 的静态方法与私有变量,协议 protocol 
- STL之multiset中equal_range,multimap中的equal_range,bitset容器,string字符串操作,lambda表达式
- 数组与malloc、new与malloc的区别