1. 程式人生 > >【LeetCode】#141環形連結串列(Linked List Cycle)

【LeetCode】#141環形連結串列(Linked List Cycle)

【LeetCode】#141環形連結串列(Linked List Cycle)

題目描述

給定一個連結串列,判斷連結串列中是否有環。
為了表示給定連結串列中的環,我們使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該連結串列中沒有環。

示例

示例 1:

輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:連結串列中有一個環,其尾部連線到第二個節點。

示例 2:

輸入:head = [1,2], pos = 0
輸出:true
解釋:連結串列中有一個環,其尾部連線到第一個節點。

示例 3:

輸入:head = [1], pos = -1
輸出:false
解釋:連結串列中沒有環。

Description

Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

解法

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null || head.next==null){
            return false;
        }
        
        ListNode fast = head.next;
        ListNode slow = head;
        
        while(fast!=slow){
            if(fast==null || fast.next==null){
                return false;
            }else{
                slow = slow.next;
                fast = fast.next.next;
            }
        }
        return true;
    }
}