Linked List Cycle (Medium)
Description
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Analysis
O(1) Space.循环遍历每个节点。把每个节点的next断开指向自己。如果这种情况出现环。
则说明原来就有环存在
My Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
* 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||head->next==NULL) return false; ListNode* p = head; while(head->next){ p = head->next; if(p==head) return true; head->next = head; head = p; } return false; } };
|