142. Linked List Cycle II
来源:互联网 发布:mac铁锈红怎么样 编辑:程序博客网 时间:2024/05/01 03:57
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.
Follow up:
Can you solve it without using extra space?
/** * 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) {if (head == NULL) return NULL;int len = cycleLen(head);if (len == 0) return NULL;ListNode* faster = head;ListNode* slower = head;while (len--){faster = faster->next;}while (faster != slower){faster = faster->next;slower = slower->next;}return slower;}private:int cycleLen(ListNode* head){ListNode* faster = head;ListNode* slower = head;bool hasCycle = false;while (faster->next&&faster->next->next){faster = faster->next->next;slower = slower->next;if (faster == slower){hasCycle = true;break;}}if (!hasCycle) return 0;int len = 1;faster = faster->next->next;slower = slower->next;while (faster != slower){faster = faster->next->next;slower = slower->next;len++;}return len;}};
0 0
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- zhangjiangtao BestCoder 2nd Anniversary Wool
- Git、GitHub的使用和MyEclipse环境下的集成
- java反射
- HTML5 IndexDB 用户本地化存储离线数据库的使用
- Glide总结
- 142. Linked List Cycle II
- php多文件上传
- stored property "text" without initial value prevents synthesized initializers
- 图像缩放算法(用过了邻近差值算法)
- 签到
- java中的Static class
- 为什么C++类定义中,数据成员不能被指定为自身类型,但可以是指向自身类型的指针或引用?
- POJ-1573-Robot Motion
- C++函数重载案例