141. Linked List Cycle (Easy)
来源:互联网 发布:安卓魔音软件 编辑:程序博客网 时间:2024/05/29 19:13
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
Solution:
C:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */bool hasCycle(struct ListNode *head) { if(head == NULL || head->next == NULL) { return false; } if(head->next == head) { return true; } struct ListNode* low = head; struct ListNode* fast = head; while(low && fast) { low = low->next; // low指针一次走一步 fast = fast->next; if(fast != NULL) { fast = fast->next; // fast指针一次走两步 } if(low == fast) { //两个指针相遇表示存在环 return true; } } return false;}
最开始犯了个低级错误,把while循环里的if(low == fast)判断写到while循环的最前面了,所以提交一直不通过,因为low和fast最开始就是相等的,都指向head,应该在low和fast开始走之后再判断是否相等。
0 0
- 141. Linked List Cycle(Linked List-Easy)
- 141. Linked List Cycle (Easy)
- 141. Linked List Cycle [easy] (Python)
- Leetcode 141. Linked List Cycle (Easy) (cpp)
- 【LeetCode】141.Linked List Cycle(easy)解题报告
- 【Leetcode-Easy-141】Linked List Cycle
- LeetCode-Easy刷题(32) Linked List Cycle
- 141.Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- uva 10012How Big Is It?
- 回归提升树 算法
- MySQL数据备份与还原
- Java多线程生产者和消费者的例子
- SQL索引详解
- 141. Linked List Cycle (Easy)
- 数列(矩阵乘法+快速幂)
- Java设计模式15——命令模式
- 我的嵌入式学习第一天
- something about my intern interview
- Android SQL
- 《深入理解Java虚拟机》读书笔记7
- 第十二周 项目3-图遍历算法实现
- 《用Python做科学计算》学习笔记(2)--函数库介绍