linked-list-cycle
来源:互联网 发布:青岛大学网络教学平台 编辑:程序博客网 时间:2024/06/03 13:06
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:思想很简单,定义快慢指针,看它们是否会相遇
在写法上需要注意一下while循环的条件。
下面是两种写法:
代码:
1、
/** * 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) { if(head==NULL || head->next==NULL) return false; ListNode *slow = head; ListNode *fast = head->next; while(slow!=NULL && fast!=NULL){//注意循环条件,这样写循环体里不需要判断它俩是否为空,下一次跳出就可以了 if(slow==fast) return true; slow = slow->next; fast = fast->next; if(fast!=NULL)//这里需要加这样的判断条件避免出现对空指针取next发生段错误 fast = fast->next; } return false; }};
2、
/** * 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) { if(head==NULL || head->next==NULL) return false; ListNode *slow = head; ListNode *fast = head;//这里由于定义的时候二者都指向链表头,所以循环里只能先后移后判断是否相等 while(fast!=NULL && fast->next!=NULL){ //关于循环条件,由于用到了fast->next->next,所以需要保证fast->next不为空 //而判断fast->next不为空的前提需要保证fast不为空,否则判断fast->next的时候就会出错 slow = slow->next;//这里因为直接后移,所以循环条件就需要加一些判断,而不能简单地判断二者不为空 fast = fast->next->next; if(slow==fast) return true; } return false; }};
阅读全文
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- LeetCode | Linked List Cycle
- java 构建和运行
- vim下注释多行
- app\build\intermediates\res\merged\debug\values-v23\values-v23.xml 编译出错的问题
- tensorflow学习笔记(一):安装与调试
- 预处理阶段所要做的工作
- linked-list-cycle
- php面试题分享(四)
- python:raw_input和input区别
- [牛客网,剑指offer,python] 矩阵覆盖
- arduino学习
- RabbitMQ 入门 Helloworld
- MySQL双主一致性架构优化 | 架构师之路
- 保护个人隐私,你需要养成这8个习惯
- 《Linux内核设计与实现》学习笔记1——进程管理