Linked List Cycle II
2015-03-26 23:17
134 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null)return null;
ListNode slow=head;
ListNode fast=head;
do{
if(fast==null||fast.next==null)return null;
fast=fast.next.next;
slow=slow.next;
} while(fast!=slow);
slow=head;
while(slow.val!=Integer.MAX_VALUE){
//这样可以通过。。。投机?
slow.val=Integer.MAX_VALUE;
slow=slow.next;
}
return slow;
}
}
null.
Follow up:
Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null)return null;
ListNode slow=head;
ListNode fast=head;
do{
if(fast==null||fast.next==null)return null;
fast=fast.next.next;
slow=slow.next;
} while(fast!=slow);
slow=head;
while(slow.val!=Integer.MAX_VALUE){
//这样可以通过。。。投机?
slow.val=Integer.MAX_VALUE;
slow=slow.next;
}
return slow;
}
}
相关文章推荐
- leetcode之Linked List Cycle II
- Linked List Cycle II
- LeetCode Linked List Cycle II 计算带环的链表的起点
- Linked List Cycle II
- [Leetcode]Linked List Cycle II
- Linked List Cycle II
- 【leetcode】【单链表】【142】Linked List Cycle II
- Linked List Cycle II
- leetcode:linked_list_cycle_II
- leetcode--Linked List Cycle II
- leetcode Linked List Cycle II
- 142. Linked List Cycle II
- LeetCode刷题(C++)——Linked List Cycle II(Medium)
- Linked List Cycle II || LeetCode
- Leetcode#142(链表)-Linked List Cycle II
- LeetCode(142)——Linked List Cycle II
- LeetCode Linked List Cycle II
- Leetcode_linked-list-cycle-ii
- [Leetcode][python]Linked List Cycle/Linked List Cycle II
- linked-list-cycle-ii——链表,找出开始循环节点