LeetCode 141 Linked List Cycle(链表判环)
2017-04-18 21:14
483 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目大意:不使用额外空间的情况下,判断链表中有没有环。
解题思路:“快慢指针”,使用两个指针slow和fast,slow每次向后移动一步,fast每次向后移动两步,如果两个指针相遇,说明链表中存在环,反之则无环。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode* slow = head;
struct ListNode* fast = head;
if(!head) return false;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(fast == slow) return true;
}
return false;
}
Follow up:
Can you solve it without using extra space?
题目大意:不使用额外空间的情况下,判断链表中有没有环。
解题思路:“快慢指针”,使用两个指针slow和fast,slow每次向后移动一步,fast每次向后移动两步,如果两个指针相遇,说明链表中存在环,反之则无环。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode* slow = head;
struct ListNode* fast = head;
if(!head) return false;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(fast == slow) return true;
}
return false;
}
相关文章推荐
- 【leetcode】【单链表】【141】Linked List Cycle
- [LeetCode-141] Linked List Cycle(判断链表是否有环)
- leetcode_c++:链表:Linked List Cycle(141)
- Leetcode 141/142 (链表题) Linked List Cycle && Linked List Cycle II
- [leetcode 141] Linked List Cycle----判断链表是否为循环链表
- 【LeetCode-面试算法经典-Java实现】【141-Linked List Cycle(单链表中有环)】
- 链表-leetcode 141 Linked List Cycle
- leetcode_141_Linked List Cycle
- leetcode--Linked List Cycle--判断链表是否有环
- LeetCode: Linked List Cycle [141]
- [LeetCode] Linked List Cycle II 单链表中的环之二
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [LeetCode] Linked List Cycle II 链表环起始位置
- Leetcode_141_Linked List Cycle
- [LeetCode] Linked List Cycle 单链表中的环
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- LeetCode:Linked List Cycle--链表快慢指针实现求链表中位和查找链表中是否存在环
- LeetCode: Linked List Cycle [141]
- Linked List Cycle leetcode java (链表检测环)
- Linked List Cycle 有环的链表@LeetCode