LeetCode 141: 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?

思路

设两个指针即快慢指针,只要是一个环,那么跑得快的总能追上跑得慢的。

代码

C语言版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode* fast = head;
struct ListNode* slow = head;
while ( fast && fast -> next ){
fast = fast -> next -> next;
slow = slow -> next;
if (fast == slow){
return true;
}
}
return false;
}

分享到 评论