leetcode 141|142. Linked List Cycle 1|2
来源:互联网 发布:mac地址查询厂商设备 编辑:程序博客网 时间:2024/06/06 04:05
141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路就是两个指针p,q
p一次走一步
q一次走两步
如果还能相等,就说明有个环
/** * 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) { ListNode *slow = head; ListNode *fast = head; while(fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow ==fast) return 1; } return 0; }};
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { ListNode *slow = head; ListNode *fast = head; while(fast && fast->next) { slow = slow->next; fast = fast->next->next; if (fast == slow) { slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return fast; } } return NULL; }};
阅读全文
0 0
- leetcode 141|142. Linked List Cycle 1|2
- LeetCode-141&142.Linked List Cycle
- LeetCode || Linked List Cycle 1&2
- LeetCode(141)Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode: Linked List Cycle [141]
- [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
- [Leetcode]#141 Linked List Cycle
- leetCode #141 Linked List Cycle
- leetcode: (141) Linked List Cycle
- Unity3D-将美术提供的图片当做字体使用(普通图片自动生成Custom font)
- macos 重围管理员帐户
- 大话设计模式读书笔记之建造者模式
- 2.2网站的高可用架构之高可用服务
- The entity name must immediately follow the '&' in the entity reference.
- leetcode 141|142. Linked List Cycle 1|2
- 教程篇(5.4) NSE4 17. 入侵防御 ❀ 飞塔 (Fortinet) 网络安全专家
- android 在子线程中使用Toast等功能
- js基本知识点总结-----js运算符
- 大数据批处理框架 Spring Batch
- Dubbox 环境搭建
- Activity,Fragment,Service的生命周期总结
- Linux下串口通信详解(下)读写串口及关闭串口
- 二叉树(未完成)