Linked List Cycle II
来源:互联网 发布:园林设计软件有哪些 编辑:程序博客网 时间:2024/06/05 09:33
https://oj.leetcode.com/problems/linked-list-cycle-ii/
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
Follow up:
Can you solve it without using extra space?
这题其实是固定做法,首先先用Linked List Cycle的做法找到第一个相交点,
第二,然后把慢指针返回头指针,然后快慢指针都一步步走next,然后再找到相交点,然后就算是找到了。
给出代码:
public ListNode detectCycle(ListNode head) { ListNode one_step = head, two_step = head; while(one_step != null && two_step != null){ if(two_step.next == null || one_step.next == null){ return null; } one_step = one_step.next; two_step = two_step.next.next; if(one_step == two_step) break; } if(one_step == null || two_step == null) return null; one_step = head; while(one_step != two_step){ one_step = one_step.next; two_step = two_step.next; } return one_step; }
0 0
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 00-自测4. Have Fun with Numbers (20)
- 安卓编程 使EditText无法输入只能进行复制等操作
- POJ 2661 Factstone Benchmark (斯特灵公式)
- 00-自测5. Shuffling Machine (20)
- C++ 去学就好
- Linked List Cycle II
- JavaScript with关键字
- 苹果取代Windows成为了最脆弱了系统
- Swift UI专项训练1 交互
- 链表、头指针、头结点、第一个结点的区别与联系
- 面向对象的总结(2)
- nyoj16矩形嵌套
- bzoj 2146: Construct
- Handler的基本使用