[LeetCode] Linked List Cycle 單鏈表中的環
阿新 • • 發佈:2018-12-27
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
這道題是快慢指標的經典應用。只需要設兩個指標,一個每次走一步的慢指標和一個每次走兩步的快指標,如果連結串列裡有環的話,兩個指標最終肯定會相遇。實在是太巧妙了,要是我肯定想不出來。程式碼如下:
C++ 解法:
class Solution { public: bool hasCycle(ListNode *head) { ListNode*slow = head, *fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; } };
Java 解法:
public class Solution { public booleanhasCycle(ListNode head) { ListNode slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; } }
類似題目: