019-141-Linked List Cycle 判断链表是否有环
2018-01-13 23:01
351 查看
Problem
Given a linked list, determine if it has a cycle in it.Follow up:
Can you solve it without using extra space?
Solution
解决方法:龟兔赛跑。快慢指针。/** * 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) { bool is_circle = false; ListNode* slow = head; ListNode* fast = head; while(slow != NULL && fast !=NULL){ slow = slow->next; if(fast->next != NULL){ fast = fast->next->next; }else{ break; } if(slow == fast){ is_circle = true; break; } } return is_circle; } };
解法2:使用哈希表。建立一个哈希表,从链表开始逐个访问节点,当发现有重复的节点的时候,可以判断链表为有环。
More
可以找到链表环开始的节点并返回该节点吗?参考我的博文020-142-Linked List Cycle II相关文章推荐
- 141 Linked List Cycle(判断链表是否有环Medium)
- [LeetCode-141] Linked List Cycle(判断链表是否有环)
- [leetcode 141] Linked List Cycle----判断链表是否为循环链表
- 020-142-Linked List Cycle II 判断链表是否有环并返回环的起点
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- [Leetcode] Linked list cycle ii 判断链表是否有环
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- 链表-Linked List Cycle II(判断一个链表是否有环)
- 判断链表是否有环 Linked List Cycle
- LeetCode OJ 之 Linked List Cycle (判断链表是否有环)
- LeetCode | Linked List Cycle(判断链表是否有环)
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- 判断链表是否有环 Linked List Cycle, Linked List Cycle II
- linked-list-cycle——链表、判断是否循环链表、快慢指针
- leetCode-linkedListCycle判断链表是否有环
- Linked List Cycle 判断链表是否有环
- [Leetcode] Linked list cycle 判断链表是否有环
- Linked List Cycle-- 判断一个单向链表中是否有环存在
- Linked List Cycle:判断链表是否有环
- Linked List Cycle(判断链表是否有环)-python