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) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
}
输入链表为空时,没有环,返回false。
因为fast指针比slow指针走得快,所以只要判断fast指针是否为空就行。由于fast指针一次走两步,所以当fast.next可能已经为空(当fast为尾结点时),fast.next.next将会导致NullPointerException异常,所以在while循环中要判断fast.next是否为空