[LeetCode] Linked List Cycle
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?
Solution:
1. The most basic method is to use a set to store all existing pointers. If a duplicate occurs, a ring exists. If no duplicate exists, no ring exists.
/** * 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* p = head; set
s; while(p!=NULL){ if(s.find(p)!=s.end()){ return true; } s.insert(p); p=p->next; } return false; }};
2. Double pointer method. Set two pointers. one pointer takes one step at a time and the other pointer takes two steps at a time. If two pointers meet each other, a ring exists. If you do not meet each other, it indicates that there is no ring. See specific: http://blog.csdn.net/kangrydotnet/article/details/45154927
/** * 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* one = head; ListNode* two = head; while(two!=NULL && two->next!=NULL){ one=one->next; two=two->next->next; if(one==two){ return true; } } return false; }};