题目链接: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?
*
*/
public class LinkedListCycle {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
// 16 / 16 test cases passed.
// Status: Accepted
// Runtime: 332 ms
// Submitted: 0 minutes ago
// 设置两个指针,一个快一个慢,快的指针每次三步,慢的指针每次走一步,如果快指针和慢指针相遇,则说明有环。
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode p = head.next;
ListNode q = head;
while(true) {
for (int i = 0; i < 3; i++) {
if(p.next != null) p = p.next;
else return false;
if(p == q ) return true;
}
q = q.next;
}
}
// 16 / 16 test cases passed.
// Status: Accepted
// Runtime: 318 ms
// Submitted: 0 minutes ago
// 设置两个指针,一个快一个慢,快的指针每次两步步,慢的指针每次走一步,如果快指针和慢指针相遇,则说明有环。
public boolean hasCycle1(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(fast == slow) return true;
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}