#Leetcode# 141. Linked List Cycle
阿新 • • 發佈:2018-11-30
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?
程式碼:
/** * 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; } };
快慢指標 如果是個環的話那麼快慢指標一定會遇到! 第一次遇到快慢指標的問題居然是在連結串列裡 畢竟連結串列我還沒看很懂啊