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?

判断一个链表中是否有环存在,用快慢指针来解决,设定两个指针fast和slow都指向head,我们让fast = fast.next.next,slow = slow.next,如果存在环,fast和slow就会相遇,因此当fast == slow时我们就返回true, 否则返回false。代码如下:
/**
 * 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 fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast)
                return true;
        }
        return false;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2276248
今日推荐