Linked List Cycle
来源:互联网 发布:淘宝代销怎么样 编辑:程序博客网 时间:2024/06/15 04:50
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断一个单链表里是否有循环,这个问题以前在一本书上见过,具体思路是这样的:
定义两个节点,都从头开始,一个每次走两步,另一个每次走一步,如果有循环,那么这两个节点肯定会相遇。
具体代码如下:
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)return false;
ListNode *tmpFast = head;
ListNode *tmpSlow = head;
do
{
if(tmpFast!=NULL)
tmpFast = tmpFast->next;
if(tmpFast!=NULL)
tmpFast = tmpFast->next;
if(tmpFast==NULL)
return false;
tmpSlow = tmpSlow->next;
} while (tmpFast != tmpSlow);
return true;
}
};
void main()
{
ListNode *a = new ListNode(3);
a->next = a;
/*a->next = new ListNode(2);
a->next->next = new ListNode(0);
a->next->next->next = new ListNode(-4);
a->next->next->next->next = a->next;*/
Solution s;
bool cycle = s.hasCycle(a);
while(1);
}
- 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
- Android 防止短时间内重复点击技巧
- ios开发学习笔记(这里一定有你想要的东西,全部免费)
- AspectJ 学习
- 5.4.1 在 C# 中实现选项类型
- java.lang.IllegalArgumentException: Invalid lookup id
- Linked List Cycle
- UIImagePickerController详解
- python操作mysql范例(增删查改)
- Java连接sql数据库
- (更新中)学习Android的反射机制的总结和查阅资料的记录
- Android--sharepreference总结
- KMP字符串模式匹配详解
- 文本框+模糊查询+下拉框效果 js
- Android 获取IP地址