王廷瑋|數位醫療|智慧醫療: 141. Linked List Cycle WFU

2024年7月6日 星期六

141. Linked List Cycle

141. Linked List Cycle


給定一個鏈表的頭節點 head,判斷該鏈表中是否存在環。

如果在鏈表中存在某個節點,可以通過不斷地跟隨下一個指針再次到達該節點,則鏈表中存在環。在內部,pos 用於表示尾部的下一個指針連接到的節點的索引。注意,pos 並不作為參數傳遞。

如果鏈表中存在環,返回 true。否則,返回 false。

範例 :

輸入:head = [3,2,0,-4], pos = 1 輸出:true 解釋:鏈表中存在一個環,其中尾部連接到第 1 個節點(0 索引)。


Python


# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

from typing import Optional

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False

slow = head
fast = head.next

while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next

return True

18.98MB, 47ms


C++


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr) {
return false;
}

ListNode* slow = head;
ListNode* fast = head->next;

while (slow != fast) {
if (fast == nullptr || fast->next == nullptr) {
return false;
}
slow = slow->next;
fast = fast->next->next;
}

return true;
}
};

10.47MB, 12ms


Javascript


/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/

/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if (head === null || head.next === null) {
return false;
}

let slow = head;
let fast = head.next;

while (slow !== fast) {
if (fast === null || fast.next === null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}

return true;
};

52.92MB, 66ms