[LeetCode]Linked List Cycle
来源:互联网 发布:网络教育介绍 编辑:程序博客网 时间:2024/06/06 23:37
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Analysis:
two pointers.One pointer is slow (1 step a time)
One pointer is fast (2 steps a time)
If there is a cycle, the two pointers will eventually meet (equal).
java
public boolean hasCycle(ListNode head){if(head == null || head.next == null) return false;ListNode p1 = head;ListNode p2 = head;while(p1!=null){p1 = p1.next;if(p2.next!=null)p2 = p2.next.next;else return false;if(p1 == p2)return true;}return false;}
c++
bool hasCycle(ListNode *head) { if(head == NULL) return false; ListNode *slow = head; ListNode *fast = head->next; while(slow !=NULL && fast !=NULL){ if(slow == fast) return true; slow = slow->next; fast = fast->next; if(fast ==NULL) return false; fast = fast->next; } return false; }
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode] - Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode]Linked List Cycle
- 【LeetCode】Linked List Cycle
- Linked List Cycle - LeetCode
- 【LeetCode】Linked List Cycle
- Linked List Cycle -- LeetCode
- 学习JavaScript的最佳方法
- 用JavaScript读取和保存文件
- Android实现后台长期监听时间变化
- the thought
- W3C 用于在 web 应用中处理文件的 API(W3C File API for representing file objects in web applications)
- [LeetCode]Linked List Cycle
- 通过 File API 使用 JavaScript 读取文件
- 使用 Chrome 开发工具调试异步 JavaScript(Debugging Asynchronous JavaScript with Chrome DevTools)
- Linux下printf输出字符串的颜色
- criterial查询
- OpenStreetMap 获取地图数据
- Getting Started with NHibernate and ASP.NET MVC- CRUD Operations
- dede--新增文章
- UIImageView动画实现