File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Author: Annie Kim, [email protected]
3
+ Date: Nov 9, 2013
4
+ Problem: Linked List Cycle
5
+ Difficulty: Easy
6
+ Source: http://oj.leetcode.com/problems/linked-list-cycle/
7
+ Notes:
8
+ Given a linked list, determine if it has a cycle in it.
9
+ Follow up:
10
+ Can you solve it without using extra space?
11
+
12
+ Solution: two pointers.
13
+ */
14
+
15
+ /* *
16
+ * Definition for singly-linked list.
17
+ * struct ListNode {
18
+ * int val;
19
+ * ListNode *next;
20
+ * ListNode(int x) : val(x), next(NULL) {}
21
+ * };
22
+ */
23
+ class Solution {
24
+ public:
25
+ bool hasCycle (ListNode *head) {
26
+ if (!head || !head->next ) return false ;
27
+ ListNode *back = head, *front = head->next ->next ;
28
+ while (true )
29
+ {
30
+ if (front == back) return true ;
31
+ if (!front || !front->next ) return false ;
32
+ front = front->next ->next ;
33
+ back = back->next ;
34
+ }
35
+ }
36
+ };
You can’t perform that action at this time.
0 commit comments