141.[LeetCode]Linked List Cycle
来源:互联网 发布:软件测试简历模板 编辑:程序博客网 时间:2024/05/16 06:36
题意:找一个单链中是否有环
我的解法
遍历单链,每次遍历 判断该节点的next 是否指向 head,如果指向说明是有环的,如果没指向则移动到下一个并把此节点的next指向head—缺点:会破坏此链,不过时间复杂度只要O(n)
class Solution {public: bool hasCycle(ListNode *head) { if(head == NULL) return false; ListNode *temp = head->next,*next; // 连续申明两个指针 head->next = head; while(temp != NULL){ next = temp->next; if(next == head) return true; temp->next = head; temp = next; } return false; }};
另一种方法
思路就是设定两个指针一起来遍历整个链,一个遍历的速度快,另一个的慢,如果有环的话,其中快的总会指向慢的,如果快的先指向null说明无环
class Solution {public: bool hasCycle(ListNode *head) { if(head == NULL || head->next == NULL) return false; ListNode *slow = head,*fast = head->next; while(slow != fast){ if(fast == NULL || fast->next == NULL) return false; slow = slow->next; fast = fast->next->next; // fast前进更快 } //一旦相等,说明有环 return true; }};
另另一 种方法
使用hashset
//这是java的public boolean hasCycle(ListNode head) { Set<ListNode> nodesSeen = new HashSet<>(); while (head != null) { if (nodesSeen.contains(head)) { return true; } else { nodesSeen.add(head); } head = head.next; } 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
- 组合数学-色数
- HDU 2030 汉字统计(汉字字符串)
- #include预处理机制详解
- 聊一聊CommonJS,Requirejs,SeaJS,AMD,CMD之间需要理清的关系
- 实战网卡bond
- 141.[LeetCode]Linked List Cycle
- CSU 1510 Happy Robot DP
- 关于equals和hashcode方法
- HDU 2031 进制转换(模拟)
- 机器学习总结
- Java IO流分析整理
- bzoj 3998(后缀自动机)
- Java笔记---Hadoop 2.7.1下WordCount程序详解
- iOS 视图控制器转场详解