Linked List Cycle II Java
来源:互联网 发布:错误推算法 编辑:程序博客网 时间:2024/06/06 21:35
/*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?*///Runner Technique Again//Two points: slow and fast, //1.slow: move one step at time//2.fast: move two steps at time//3.while two points(slow and fast) are encounter => hasCycle => break//4.Set slow point back to head to find node point of cycle begin. public class Solution { public ListNode detectCycle(ListNode head) { if (head == null)return null;if (head.next == null)return null;//handle the base case of {1} tail connects to head itselfif(head.next ==head) return head;ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;if (slow == fast) {break;}}//handle the case of noCycle that make sure there is cycle existif(slow==null || fast ==null || fast.next==null){return null;}//move slow point to the headslow=head;while(slow!=fast){slow=slow.next;fast=fast.next;}//when two point slow and fast encounter again, //return either slow or fast for point of cycle begin return slow; }}
0 0
- Linked List Cycle II Java
- Linked List Cycle II (Java)
- JAVA-Linked List Cycle I&&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
- 青春
- 算法导论 | 第25章 所有结点对的最短路径问题
- openOffice Module Build Order
- 修改maven路径
- 1010
- Linked List Cycle II Java
- sadf
- 学习笔记 Java_封装 2014.7.11
- Oracle 10g创建表空间的完整步骤详解
- 四大家族地方筷子兄弟快乐幸福寡廉鲜耻;下册;
- cocos2d-x-2.2.4 (三) 整理MyGame工程
- 只是看到这些科学发过来重点防控中心对方快乐幸福
- 让你轻松访问goole
- 面试算法(九)二进制中1的个数