您的位置:首页 > 其它

Linked List Cycle I II

2015-07-11 22:31 302 查看


Linked List Cycle



Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?



Keep two kinds of pointers: faster pointer and slower pointer and keep fixed interval between them. For example, faster pointer will go one step faster than the slower pointer. If the linked list is a cyclic
list, faster pointer will end up in catching up with slower pointer. If the linked list is an acyclic list, faster pointer will reach null in the end.




/**
* Definition for singly-linked list.
* class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null)
return false;

ListNode slower = head;
ListNode faster = head;

while (faster.next != null && faster.next.next != null) {
slower = slower.next;
faster = faster.next.next;

if (slower == faster)
return true;
}

return false;
}

}
Linked
List Cycle II





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?


/**
* 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 faster = head;
ListNode slower = head;

while (faster.next != null && faster.next.next != null) {
slower = slower.next;
faster = faster.next.next;

if (slower == faster) {
slower = head;

while (slower != faster) {
slower = slower.next;
faster = faster.next;
}

return slower;
}
}

return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: