Linked List Cycle
来源:互联网 发布:js的display 编辑:程序博客网 时间:2024/06/05 03:25
问题:判断链表是否有环。
分析:利用快慢指针slow,fast
slow指针每次走一步,fast指针每次走两步,倘若存在环,则slow和fast必定在某一时刻相遇。
由于fast指针走的比slow快所以循环的时候只需要判断fast和fast->next不为空,判断fast->next是因为防止出现fast->NULL->next这种情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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 *fast,*slow;
if
(head==NULL)
return
false
;
slow=head;
fast=head->next;
while
(fast!=NULL && fast->next!=NULL)
{
if
(slow==fast)
return
true
;
slow=slow->next;
fast=fast->next->next;
}
return
false
;
}
};
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- LeetCode | Linked List Cycle
- 2、广域网基础知识……
- Xms Xmx PermSize MaxPermSize 区别
- GDB详解
- SqlBulkCopy使用Demo
- C程序编译过程浅析
- Linked List Cycle
- 返回多个list合集map于前台 js读取
- [IOS]通过UIPageControl+UIScrollView实现图片循环轮播
- 《Ext江湖》学习笔记--JS中变量、对象和数组的定义与使用
- 根据手机的分辨率从 dp 的单位 转成为 px
- ListIterator迭代器
- SQLite一条SQL语句插入多条记录失败的问题
- java容器(一)
- GUN ARM汇编中标号的引用在汇编和C语言中区别