Leetcode_Linked_List --141. Linked List Cycle [easy]
阿新 • • 發佈:2018-12-15
Given a linked list, determine if it has a cycle in it. 給定一個連結串列,判斷它是否有環
Follow up: Can you solve it without using extra space?
Solution:
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 """ 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 == NULL){ return false; } ListNode* fast = head; ListNode* slow = head; while (fast && fast->next){ fast = fast->next->next; slow = slow->next; if (slow == fast){ return true; } } return false; } };
其實這道題的程式碼很簡單,關鍵在於理解這個程式碼的解法。 要求連結串列是否有環,需要設定兩個指標,一個快指標fast一個慢指標slow,fast每次走兩步,slow每次走一步,如果連結串列有環的話,fast和slow必然會在連結串列環上相遇,這個好比時鐘的秒針和分針。並且通過證明可以知道fast和slow相遇的時,slow必然沒有走完環的一圈(極限情況是slow剛好走完一圈到達環的入口處)。理解了這個原理之後就可以編寫程式碼了。