1. 程式人生 > >#Leetcode# 141. Linked List Cycle

#Leetcode# 141. Linked List Cycle

https://leetcode.com/problems/linked-list-cycle/

 

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

Follow up:
Can you solve it without using extra space?

Accepted 324,757 Submissions 938,662 Seen this question in a real interview before?

程式碼:

/**
 * 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) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
        return false;
    }
};

  快慢指標 如果是個環的話那麼快慢指標一定會遇到! 第一次遇到快慢指標的問題居然是在連結串列裡 畢竟連結串列我還沒看很懂啊