题目地址:https://leetcode.com/problems/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?
题目要求判断一个单链表是不是有环,假设有两个指针p和q,都从前往后遍历这个链表,这两个指针唯一的区别就是向后移动的速度不一样,p一次移动一个位置,即p=p.next,q一次移动两个位置,即q=q.next.next。
如果p和q相遇了,那么这个链表内部存在环。因为速度不一样么,快的总会超过慢的。如果p和q其中一个已经是null了,那么也就是说这个链表中没有环。
代码实现如下:
public class LinkedListCycle {
public boolean hasCycle(ListNode head) {
if (head == null)
return false;
ListNode p = head;
ListNode q = head.next;
if (p == q)
return true;
if (q != null)
q = q.next;
while (p != null && q != null) {
if (p == q) {
return true;
}
p = p.next;
if (q.next != null)
q = q.next.next;
else
q = null;
}
return false;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(1);
ListNode node3 = new ListNode(1);
ListNode node4 = new ListNode(1);
ListNode node5 = new ListNode(1);
ListNode node6 = new ListNode(1);
ListNode node7 = new ListNode(1);
ListNode node8 = new ListNode(1);
ListNode node9 = new ListNode(1);
ListNode node10 = new ListNode(1);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
node7.next = node8;
node8.next = node9;
node9.next = node10;
node10.next = node7;
LinkedListCycle linkedListCycle = new LinkedListCycle();
System.out.println(linkedListCycle.hasCycle(node1));
}
}