Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question.
Solution:
Tips:
one step pointer, and two step pointer to validate the list if it has cycle.
Java Code:
/**
* 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 (null == head) {
return false;
}
ListNode stepOne = head;
ListNode stepTwo = head;
do {
stepOne = stepOne.next;
stepTwo = stepTwo.next;
if (null != stepTwo) {
stepTwo = stepTwo.next;
}
} while (stepOne != null && stepTwo != null && stepOne != stepTwo);
return stepTwo != null && stepOne == stepTwo ? true : false;
}
}