LeetCode:Linked List Cycle II
来源:互联网 发布:淘宝直通车多少钱 编辑:程序博客网 时间:2024/06/06 12:54
题目描述:
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?
思路:
设置一个快指针fast,一个慢指针slow。快指针一次移动两个单位,慢指针一次移动一个单位。如图,链表进入环之后是逆时针移动,假设两个指针是在红蓝交界的地方相遇。则快指针走的距离Sf=x+y+z+y=x+2y+z,慢指针走的距离Ss=x+y。又因为Sf=2Ss,则x+2y+z=2x+2y,可得x=z。则可令fast指针重新回到head,两指针依次移动一个单位直到相遇。相遇的点即为环开始的点。
代码:
ListNode * Solution::detectCycle(ListNode * head){ if(head == NULL) return NULL; if(head->next == head) return head; ListNode * fast = head; ListNode * slow = head; while(fast != NULL && fast->next != NULL) { fast = fast->next->next; slow = slow->next; if(fast == slow) break; } if(fast == NULL || fast->next == NULL) return NULL; else { fast = head; while(fast != slow) { fast = fast->next; slow = slow->next; } return fast; }}
0 0
- 【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
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Mysql5.6安装-linux下安装二进制包
- undo段头信息以及故障处理
- chm电子书字体大小的调整
- 西安众筹投资项目 触摸古城幸福灵魂 品饮健康现酿酸奶
- 线程自动创建与销毁
- LeetCode:Linked List Cycle II
- Android传递对象的两种方法,(Serializable,Parcelable)
- UI04手势识别器
- ORACLE 启动与关闭
- zoj2676 Network Wars(0-1分数规划,最大流模板)
- LeetCode Reverse Linked List II
- spring 配置多数据源
- nextday
- 碳素结构钢的实际拉伸性能可能与规定的最小值不同