leetcode 141. Linked List Cycle 链表循环的判定 + 双指针
来源:互联网 发布:linux下c 多线程 编辑:程序博客网 时间:2024/05/16 19:34
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
本题就是判断链表是否存在循环,这个方法很棒,说实话我自己是想不到的。
代码如下:
/*class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; }}*//* * 题目要求是判断链表是否有环,leetcode上链表的题都是没有头结点的,这点大家要记住。 * 而且若链表有环,也是最后一个节点形成的环。 * 大家考虑这样一个问题,链表的环相当于一个圆形操场。假设有两个人在圆形操场上无限循环的跑, * 那么速度快的一定能追得上速度慢的。同理,若要判断一个链表是否有环,可设计快慢指针, * 当快慢指针都进入环的时候,若最终两个指针相遇,必可说明链表存在环。下面就要考虑快慢指针的步长, * 从跑操场的情况来看,不管慢的有多慢,快得有多快,最终肯定能相遇。同理,链表中, * 也可随意指定快慢指针的步长,无非就是跑的圈数多少的问题。 * */public class Solution { public boolean hasCycle(ListNode head) { if(head==null || head.next==null) return false; ListNode fast=head,slow=head; while(fast!=null && slow!=null && fast.next!=null) { slow=slow.next; fast=fast.next.next; if(fast==slow) return true; } return false; }}
下面是C++的做法,就是使用双指针来判断循环的存在与否
代码如下:
#include <iostream>#include <vector>#include <algorithm>#include <string>#include <map>#include <set>#include <climits>using namespace std;/*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* fast = head; ListNode* slow = head; while (fast != NULL && slow != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if (fast == slow) return true; } return false; }};
阅读全文
0 0
- leetcode 141. Linked List Cycle 链表循环的判定 + 双指针
- Leetcode Linked List Cycle 循环链表
- LeetCode 141. Linked List Cycle(链表循环)
- leetcode Linked List Cycle 链表的快慢指针
- Leetcode Linked List Cycle II 循环链表入口
- LeetCode 142. Linked List Cycle II(循环链表)
- (LeetCode)Linked List Cycle --- 判断循环链表
- LeetCode 141 Linked List Cycle(循环链表)(HashSet/Linked List)
- 141.leetcode Linked List Cycle(easy)[链表是否有环 快慢指针]
- leetcode---linked-list-cycle---链表中点
- Linked List Cycle 有环的链表@LeetCode
- LeetCode linked-list-cycle-ii找到链表的环
- [LeetCode] [快慢指针] 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
- openstack-nova-创建云主机代码分析
- StaggeredGridLayoutManager 瀑布流返回顶部时跳跃问题 解决办法
- 9-16 acm
- RxJava源码分析(1)
- 程序片段----弹出文件夹
- leetcode 141. Linked List Cycle 链表循环的判定 + 双指针
- 使用Halcon实现图像处理
- openwrt menuconfig恢复默认配置
- java三种方式实现键盘录入
- SpringMVC通过Controller实现页面跳转
- Spring Boots &mybatis连接数据库配置步骤
- docker中使用gitlab笔记
- 以SpringIoc的模拟实现来学习反射和xml解析
- 解决端口(8080)被占用情况