1. 程式人生 > >LeetCode[141]Linked List Cycle

LeetCode[141]Linked List Cycle

Description

Given a linked list, determine if it has a cycle in it.

  • Follow up: Can you solve it without using extra space?
  • 連結串列無環

在這裡插入圖片描述

  • 連結串列有環

在這裡插入圖片描述

連結串列無環

idea

  • 設定超時時間暴力窮舉 判斷給定的時間內,連結串列是否遍歷完成。
  • 使用Set判重 遍歷連結串列,每走一個節點都在Set中查詢是否存在,若存在則連結串列有環。 時間複雜度O(n)
  • 使用快慢指標 使用一個快指標(一次走兩步)和一個慢指標(一次走一步),如果兩個指標相遇,則連結串列有環。 時間複雜度O(n),不需要額外的儲存開銷,這種方法效能最佳。
/**
 - 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 f = head, s =head;
        while(null != f && null != s && f.next != null) {
            s = s.next;
            f = f.next.next;
            if (s == f) {
                return true;
            }
        }
        return false;        
    }
}
  • 快慢指標執行結果 在這裡插入圖片描述