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?
/**
* 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
/**
* 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;
}
}
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;
}
}
/**
* 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;
}
}