Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
My Answer:
/**
* 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 stepOne = head;
ListNode stepTwo = head;
while(true){
if(stepTwo == null){
return false;
}
stepTwo = stepTwo.next;
if(stepTwo == null){
return false;
}
stepTwo = stepTwo.next;
stepOne = stepOne.next;
if(stepTwo == stepOne){
return true;
}
}
}
}
题目来源:https://oj.leetcode.com/problems/linked-list-cycle/