[LeetCode OJ]Linked List Cycle
来源:互联网 发布:自学计算机游戏编程 编辑:程序博客网 时间:2024/06/03 14:46
Given a linked list, determine if it has a cycle in it.
标准做法是使用两个指针,一个每次往前走2步,一个每次往前走1步,如果两个指针相遇,即说明链表有环,时间复杂度为O(N),空间复杂度为O(1)。
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: bool hasCycle(ListNode *head) { if (head == NULL) { return false; } if (head->next == NULL) { return false; } if (head->next == head) { return true; } ListNode *y = head->next; ListNode *x = head->next->next; while(x != NULL && y != NULL) { x = x->next; if (x == NULL) break; x = x->next; y = y->next; if (x == y) break; } return x == y; }};
标准做法是使用两个指针,一个每次往前走2步,一个每次往前走1步,如果两个指针相遇,即说明链表有环,时间复杂度为O(N),空间复杂度为O(1)。
这篇文章蛮有帮助,也是按着这个思路实现的代码:经典面试题 之 单链表找环
0 0
- LeetCode OJ:Linked List Cycle
- [LeetCode OJ]Linked List Cycle
- LeetCode OJ Linked List Cycle
- LeetCode OJ:Linked List Cycle II
- [LeetCode OJ] Linked List Cycle 解题报告
- LeetCode OJ Linked List Cycle II
- LeetCode OJ-141. Linked List Cycle(链表找环)
- LeetCode OJ 141. Linked List Cycle
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- github 学习
- 1016
- OpenMP和MPI的区别(不断总结、汇总、更新中)
- 把两个排好序的数组,升序插入到另一个数组
- 表、触发器、事务、存储过程
- [LeetCode OJ]Linked List Cycle
- 基于事件的 JavaScript 编程:异步与同步
- leetcode N-Queens
- Android NDK调试出错Unknown Application ABI, Unable to detect application ABI's的解决方案
- SpringMVC查询返回集合,不能自定义字段对象的解决方法
- 为什么小电容通高频,大电容通低频
- 数据结构之广义表(头尾链表存储)基本操作
- NLog日志管理工具--入门实例
- hdu 1051 Wooden Sticks(贪心策略)