题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
给定一个链表,判断链表中否有环。
补充:
你是否可以不用额外空间解决此题?
思路:使用快慢指针,如果快指针和慢指针可以相遇,则证明该链表中存在环。思路同找出链表中环的入口
代码如下:>-<
/**
* 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 slow = head;
ListNode fast = head;
while(fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
return true;
}
return false;
}
}