带环链表
题目
给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
挑战
不要使用额外的空间
题解
如果链表有环,则使用快慢指针遍历,终究会有一个时刻两指针相遇。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
public boolean hasCycle(ListNode head) {
ListNode low = head;
ListNode fast = head;
while (low!= null && fast!=null)
{
low = low.next;
if (fast.next==null)
{
return false;
}
fast = fast.next.next;
if (low == fast)
{
return true;
}
}
return false;
}
}
Last Update 2016.10.6