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?
题目大意:
判断一个单链表是否存在环。
思路:
采用快慢指针来处理。
代码如下:
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
26
27
28
29
30
31
|
/**
* 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 *slow,*fast;
if
(NULL == head || NULL == head->next)
return
false
;
slow = head;
fast = head;
fast = fast->next->next;
slow = slow->next;
while
(1)
{
if
(fast == NULL || fast->next == NULL)
return
false
;
if
(fast == slow || fast->next == slow)
return
true
;
slow = slow->next;
fast = fast->next->next;
}
return
false
;
}
};
|
总结:快慢指针
快慢指针中的快慢指的是移动的步长,即每次向前移动速度的快慢。例如可以让快指针每次沿链表向前移动2,慢指针每次向前移动1次。
快慢指针可以用来求一个单链表是否存在环,还可以用来求一个单链表的中间位置。
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837479