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 || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while(slow != fast && slow.next != null && fast.next != null && fast.next.next != null){// 注意各种情况
slow = slow.next;
fast = fast.next.next;
}
if(slow == fast) return true;
return false;
}
}