LeetCode OJ Linked List Cycle
来源:互联网 发布:淘宝网店在哪里看 编辑:程序博客网 时间:2024/06/16 06:02
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
to solve this problem is quiet easy but ingenious. Declare two pointers whose speed is twice as fast as another. When there 2 pointers are meet, there is a loop in the list.
Prove:
Suppose the 2 pointers meet after t time, which means t times movement. Then the difference is 2t - t = t, which is surely the loop's length. Notice that t will increase from 0 to max_length(the length of the list), if there is a loop in the list, we can find it.
class Solution {public: bool hasCycle(ListNode *head) { ListNode *temp_1 = head; ListNode *temp_2 = head; while (temp_2 != NULL && temp_2->next != NULL) { temp_1 = temp_1->next; temp_2 = temp_2->next->next; if (temp_1 == temp_2) { return true; } } return false; }};
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
- java.io中的字符流简单介绍
- ZOJ1003(1)
- LeetCode OJ Reverse Linked List II
- LeetCode OJ Linked List Cycle II
- 每个Java程序员必须知道的5个JVM命令行标志
- LeetCode OJ Linked List Cycle
- leetcode 之Rotate Array
- LeetCode OJ Insertion Sort List
- LeetCode OJ Sort List
- LeetCode OJ Max Points on a Line
- hdu 4463 Outlets(最小生成树)
- linux 下实线文件切割--split
- LeetCode OJ Remove Duplicates from Sorted List II
- 如何让基于对话框的MFC程序一运行起来就完全隐藏