#102 Linked List Cycle
来源:互联网 发布:php global用法 编辑:程序博客网 时间:2024/06/03 06:38
题目描述:
Given a linked list, determine if it has a cycle in it.
Example
Given -21->10->4->5, tail connects to node index 1, return true
Challenge
题目思路:Follow up:
Can you solve it without using extra space?
这是一题挺有名的龟兔赛跑问题。设两个pointer,一个slow每次走一格,一个fast每次走2格。如果有circle,那么slow和fast必会在circle中的某一点相遇。否则就没有circle。
Mycode(AC = 23ms):
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */class Solution {public: /** * @param head: The first node of linked list. * @return: True if it has a cycle, or false */ bool hasCycle(ListNode *head) { // write your code here if (head == NULL || head->next == NULL) { return false; } ListNode *slow = head, *fast = head; while (fast && fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow->val == fast->val) { return true; } } return false; }};
0 0
- #102 Linked List Cycle
- 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
- matplotlib 可视化 —— 定制 matplotlib
- Shell总结(整理)
- 修改setting的ui风格
- MongoDB-JAVA-Driver 3.2版本常用代码全整理(1) - 增删改
- 设计模式之策略模式
- #102 Linked List Cycle
- 如何更改ISE的IP核生成器中默认关联的PDF阅读器?
- 死锁
- 嵌入式学习--work2 IAR 如何建立模板
- [bug] captcha中demo运行失败(TypeError must be sequence of length 4, not 2)
- 使用Oracle Sql Developer将SQL SERVER 2008数据库移植到Oracle 11g
- 做个快乐的程序员
- 创建SpringMVC项目之使用配置文件实现
- Retrofit的简单使用方法