1. 程式人生 > >Leetcode linked-list-cycle 判斷連結串列是否有環

Leetcode 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?

給定一個連結串列,判斷連結串列中否有環。

補充:         你是否可以不用額外空間解決此題?

思路:使用快慢指標,如果快指標和慢指標可以相遇,則證明該連結串列中存在環。思路同找出連結串列中環的入口

程式碼如下:>-<

/**
 * 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;
    }
}