[leetcode141142]Linked List Cycle I II
来源:互联网 发布:做网络推广职业前景 编辑:程序博客网 时间:2024/06/09 19:14
1 Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
如何求环的长度,记住碰撞点的指针,让slow指针不停向后遍历,当再次回到碰撞点时走过的距离就是环的长度。
碰撞点到环节点 = 头结点到环节点
设环外长度为a,环长度为r,碰撞点距离环节点为b。
有a+b = s; a+b+nr = 2s;
s = nr;
i<a 时 t(i)= i;
i>=a时,t(i)=a+(i-a)%r
t(a) = t(nr+a)=t(s+a)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool hasCycle(ListNode *head) { ListNode *slow = head; ListNode *fast = head; while(NULL != fast && NULL != fast->next) //can divide only one node that have cycle or don't have cycle { slow = slow->next; fast = fast->next->next; if(slow == fast){return true;} } return false; }};
Given 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?
class Solution {public: ListNode *detectCycle(ListNode *head) { ListNode *slow = head; ListNode *fast = head; ListNode *find = head; while(NULL != fast && NULL != fast->next) //can divide only one node that have cycle or don't have cycle { slow = slow->next; fast = fast->next->next; if(slow == fast) { while(slow != find) { slow = slow->next; find = find->next; } return find; } } return NULL; }};
0 0
- [leetcode141142]Linked List Cycle I II
- Linked List Cycle I & II
- Linked List Cycle I&&II
- Linked List Cycle I / II
- Linked List Cycle I II
- Linked List Cycle I&II
- JAVA-Linked List Cycle I&&Linked List Cycle II
- Linked List Cycle I,II, Partition List
- leetcode Linked List Cycle I II
- LeetCode:Linked List Cycle I & II
- LeetCode :: Linked List Cycle I and II
- leetcode Linked List Cycle(I II)(*)
- leetcode-Linked List Cycle I & II
- LeetCode: linked list cycle I and II
- 【LeetCode】Linked List Cycle I&II
- 141+142. Linked List Cycle I+II
- LeetCode - Linked List Cycle I &II
- 142. Linked List Cycle I&II
- URL 收藏
- Linux守护进程(init.d和xinetd)
- 黑马程序员——System类,Properties类,Random类,Math类,Runtime类,Date类,Calendar类
- 近义词
- 地板的挑选和安装
- [leetcode141142]Linked List Cycle I II
- 第15章 增加转载功能和转载统计
- 可变参数求平均数
- Cocos2d-x Auto-batching 浅浅的”深入分析”
- 【转载】Jsp9个内置对象详解
- SQL LEFT JOIN
- JAVA连接FTP服务器,并上传/下载文件代码
- Android中发布release版的apk && 混淆器
- 设置最佳线程数总结