leetcode_141_ Linked List Cycle
来源:互联网 发布:污网络用语大全及解释 编辑:程序博客网 时间:2024/04/28 22:03
欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
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?
一开始使用了复杂度O(n^2)的方法,但是超时了,使用两个指针a, b。a从表头开始一步一步往前走,遇到null则说明没有环,返回false;a每走一步,b从头开始走,如果遇到b==a.next,则说明有环true,如果遇到b==a,则说明暂时没有环,继续循环。
后来使用复杂度O(n)的方法:使用两个指针slow,fast。两个指针都从表头开始走,slow每次走一步,fast每次走两步,如果fast遇到null,则说明没有环,返回false;如果slow==fast,说明有环,并且此时fast超了slow一圈,返回true。
分析:为什么有环的情况下二者一定会相遇呢?因为fast先进入环,在slow进入之后,如果把slow看作在前面,fast在后面每次循环都向slow靠近1,所以一定会相遇,而不会出现fast直接跳过slow的情况。
//复杂度O(n)的方法:使用两个指针slow,fast。两个指针都从表头开始走,slow每次走一步,fast每次走两步,如果fast遇到null,则说明没有环,返回false;如果slow==fast,说明有环,并且此时fast超了slow一圈,返回true。////分析:为什么有环的情况下二者一定会相遇呢?因为fast先进入环,在slow进入之后,如果把slow看作在前面,fast在后面每次循环都向slow靠近1,所以一定会相遇,而不会出现fast直接跳过slow的情况。class Solution {public: bool hasCycle(ListNode *head) {ListNode *fast=head;ListNode *slow=head;while( fast && slow ){fast = fast->next;if(fast)fast = fast->next;else break;slow = slow->next;if( fast == slow )return true;}return false; }};
1 0
- leetcode_141_ Linked List Cycle
- 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_138_ Copy List with Random Pointer
- 数据结构之栈
- HTTP协议与XML
- Xcode提交代码到SVN,文件右边出现UM
- 博白县办港澳通行证流程及相关费用
- leetcode_141_ Linked List Cycle
- SVD在推荐系统中的应用与实现(c++)
- json jsonp ajax
- Runtime Error!
- python日期转换
- 跨平台数据对接2
- Quartz学习笔记-Spring整合与简单使用
- 欢迎使用CSDN-markdown编辑器
- C++ STL 算法简介