Linked List Cycle-- 判断一个单向链表中是否有环存在
2013-11-03 08:46
381 查看
原题:
Given a linked list, determine if it has a cycle in it.
=>给定一个单向链表,如何判断它里面是否有环存在。
Follow up:
Can you solve it without using extra space?
=>能否不使用额外的空间来解决这个问题?
晓东分析:
这是一个经典的题目了,他的解题思路就是使用快慢指针,就像我们以前学过的初中(or小学)数学题,只要两者的速度不同,在一个环内,终归是会追上的。当然我们一般的题目都是多长时间追上啊之类的问题。很简单吧,直接看代码了。
代码实现:
执行结果:
希望大家有更好的算法能够提出来,不甚感谢。
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
Given a linked list, determine if it has a cycle in it.
=>给定一个单向链表,如何判断它里面是否有环存在。
Follow up:
Can you solve it without using extra space?
=>能否不使用额外的空间来解决这个问题?
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. } };
晓东分析:
这是一个经典的题目了,他的解题思路就是使用快慢指针,就像我们以前学过的初中(or小学)数学题,只要两者的速度不同,在一个环内,终归是会追上的。当然我们一般的题目都是多长时间追上啊之类的问题。很简单吧,直接看代码了。
代码实现:
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode *slow = head; ListNode *fast = head; while(fast != NULL && fast->next != NULL){ slow = slow->next; fast = fast->next->next; if(fast == slow) return true; } return false; } };
执行结果:
16 / 16test cases passed. | Status:Accepted |
Runtime: 76 ms |
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
相关文章推荐
- Linked List Cycle 判断一个链表是否存在回路(循环)
- 如何判断一个单向链表是否为回文链表(Palindrome Linked List)
- 链表-Linked List Cycle II(判断一个链表是否有环)
- [LeetCode-141] Linked List Cycle(判断链表是否有环)
- 判断一个单向链表中是否存在环
- [leetcode 141] Linked List Cycle----判断链表是否为循环链表
- Linked List Cycle 判断链表是否有环
- [Leetcode] Linked list cycle ii 判断链表是否有环
- leetcode--Linked List Cycle--判断链表是否有环
- leetCode-linkedListCycle判断链表是否有环
- 判断一个单向链表中是否存在环
- Linked List Cycle(判断链表是否有环)-python
- 【leetcode】Linked List Cycle II,判断链表是否有环
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- LeetCode:Linked List Cycle--链表快慢指针实现求链表中位和查找链表中是否存在环
- 判断一个单向链表中是否存在环
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- LeetCode | Linked List Cycle(判断链表是否有环)
- 如何判断一个单向链表是否存在循环的经典方法
- Linked List Cycle:判断链表是否有环