Skip to content

Commit d0470c9

Browse files
committed
Add 'Linked List Cycle'.
1 parent 2624765 commit d0470c9

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

LinkedListCycle.h

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
};

0 commit comments

Comments
 (0)