天天看點

LeetCode 141. Linked List Cycle(快慢指針)Linked List Cycle

Linked List Cycle

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 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.

LeetCode 141. Linked List Cycle(快慢指針)Linked List Cycle

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.

LeetCode 141. Linked List Cycle(快慢指針)Linked List Cycle

Example 3:

Input: head = [1], pos = -1

Output: false

Explanation: There is no cycle in the linked list.

LeetCode 141. Linked List Cycle(快慢指針)Linked List Cycle

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

題意

判斷連結清單是否有環

思路

快慢指針,慢指針一次走一步,快指針一次走兩步,如果連結清單有環,則快指針和慢指針會相遇。時間複雜度O(n),空間複雜度O(1).

代碼

/*
 * @lc app=leetcode id=141 lang=java
 *
 * [141] Linked List Cycle
 */
/**
 * 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, fast = head;
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
            if (fast != null) {
                fast = fast.next;
            } else {
                break;
            }            
            if (slow == fast) {
                return true;
            }

        }
        return false;
    }
}