LeetCode 141. Linked List Cycle
来源:互联网 发布:oracle数据库导出 编辑:程序博客网 时间:2024/05/29 07:41
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?
补充:不要使用额外空间
一开始拿到这道题时,我的想法是讲结构体ListNode中的val属性作为是否访问过的标志位,如果访问过,置0。如果后面发现ListNode的val为0,说明含有循环,并返回结果。写出第一版代码如下:
bool Solution::hasCycle(ListNode *head) { bool flag = false; while(head) { if (head->val != 0) head->val = 0; else { flag = true; break; } head = head->next; } return flag;}
细心点的小伙伴会发现,第一版的代码有明显的问题。如果第一次访问该节点的时候,该节点的val为0,则程序就会返回含有循环的结果,但是,在LeetCode上面这份代码居然通过了,应该测试数据有bug,这就很尴尬了。
改用第二种方法,快慢指针。其思想是设两个指针,一个每次走一步的慢指针和一个每次走两步的快指针,如果链表里有环的话,两个指针最终肯定会相遇。最终代码如下:
bool Solution::hasCycle(ListNode *head) { // 使用快慢指针 ListNode *fast = head, *slow = head; while(fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false;}
阅读全文
0 0
- [LeetCode]141.Linked List Cycle
- LeetCode 141. Linked List Cycle
- [Leetcode] 141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- [leetcode] 141.Linked List Cycle
- leetcode 141.Linked List Cycle
- [leetcode] 141. Linked List Cycle
- [LeetCode]141. Linked List Cycle
- 141. Linked List Cycle LeetCode
- [LeetCode]141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- LeetCode *** 141. Linked List Cycle
- [LeetCode]141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- [leetcode]141. Linked List Cycle
- leetcode-141. Linked List Cycle
- 141.[LeetCode]Linked List Cycle
- 【leetcode】141. Linked List Cycle
- 推荐给IT运维工程师必须学习的4本Linux书籍
- Java编程思想之访问权限控制
- NLP解释
- 学习python之 glob模块
- Q125:PBRT-V3,对比VolPathIntegrator::Li()和EstimateDirect()判断Medium的方式
- LeetCode 141. Linked List Cycle
- H5的 多线程Worker,缓存cache
- 读取Java的配置文件Properties
- 封包显示Listview和Imageview
- OpenFlow笔记
- shell脚本--语法篇
- Canonical将确保 Unity 7 能顺利过渡
- 排序相关——荷兰国旗问题
- zoj 1730