LeetCode141. ็ฏๅฝข้พ่กจ๐๐๐๐๐็ฎๅ
่ฏพๅไฝไธ
้ฎ้ขๆ่ฟฐ
ๅๆ้พๆฅ๏ผ141. ็ฏๅฝข้พ่กจ
็ปไฝ ไธไธช้พ่กจ็ๅคด่็น head ๏ผๅคๆญ้พ่กจไธญๆฏๅฆๆ็ฏใ
ๅฆๆ้พ่กจไธญๆๆไธช่็น๏ผๅฏไปฅ้่ฟ่ฟ็ปญ่ท่ธช next ๆ้ๅๆฌกๅฐ่พพ๏ผๅ้พ่กจไธญๅญๅจ็ฏใ ไธบไบ่กจ็คบ็ปๅฎ้พ่กจไธญ็็ฏ๏ผ่ฏๆต็ณป็ปๅ
้จไฝฟ็จๆดๆฐ pos ๆฅ่กจ็คบ้พ่กจๅฐพ่ฟๆฅๅฐ้พ่กจไธญ็ไฝ็ฝฎ๏ผ็ดขๅผไป 0 ๅผๅง๏ผใๆณจๆ๏ผpos ไธไฝไธบๅๆฐ่ฟ่กไผ ้ ใไป
ไป
ๆฏไธบไบๆ ่ฏ้พ่กจ็ๅฎ้
ๆ
ๅตใ
ๅฆๆ้พ่กจไธญๅญๅจ็ฏ ๏ผๅ่ฟๅ true ใ ๅฆๅ๏ผ่ฟๅ false ใ
็คบไพ 1๏ผ

่พๅ
ฅ๏ผhead = [3,2,0,-4], pos = 1
่พๅบ๏ผtrue
่งฃ้๏ผ้พ่กจไธญๆไธไธช็ฏ๏ผๅ
ถๅฐพ้จ่ฟๆฅๅฐ็ฌฌไบไธช่็นใ
็คบไพ 2๏ผ

่พๅ
ฅ๏ผhead = [1,2], pos = 0
่พๅบ๏ผtrue
่งฃ้๏ผ้พ่กจไธญๆไธไธช็ฏ๏ผๅ
ถๅฐพ้จ่ฟๆฅๅฐ็ฌฌไธไธช่็นใ
็คบไพ 3๏ผ

่พๅ
ฅ๏ผhead = [1], pos = -1
่พๅบ๏ผfalse
่งฃ้๏ผ้พ่กจไธญๆฒกๆ็ฏใ
ๆ็คบ๏ผ
- ้พ่กจไธญ่็น็ๆฐ็ฎ่ๅดๆฏ
[0, 104] -105 <= Node.val <= 105posไธบ-1ๆ่ ้พ่กจไธญ็ไธไธชๆๆ็ดขๅผ ใ
ไปฃ็ ๅฎ็ฐ
Java
/**
* 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 fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return false;
}
}
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
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){
return false;
}
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
if head == nil {
return false
}
fast := head
slow := head
for fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
if fast == slow {
return true
}
}
return false
}