leetcode 141. Linked List Cycle
2017-01-13 15:28
169 查看
这道题采用的比较典型的龟兔赛跑的思想,用更快的兔子套乌龟,如果存在环的话就会在兔子最终会抓到乌龟的。
/** * 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 *step_one = head; ListNode *step_two = head; while(step_two != NULL && step_two->next != NULL && step_two->next->next != NULL) { step_one = step_one->next; step_two = step_two->next->next; if(step_one == step_two) return true; } return false; } };
相关文章推荐
- leetcode Add Two Numbers
- 【Leetcode】Best Time to Buy and Sell Stock III
- LeetCode刷题笔录 Binary Tree Inorder Traversal
- [leetcode 11] Container With Most Water
- Leetcode_num7_Linked List Cycle
- leetcode 编辑距离 Edit Distance
- 【LeetCode从零单排】No.7 Reverse Integer
- LeetCode第13题--Roman to Integer(Java实现)
- Construct Binary Tree from Inorder and Postorder Traversal - LeetCode 106
- LeetCode题解:Path Sum
- LeetCode题解:Same Tree
- Leetcode Number of Digit One
- 【leetcode 43】--------Multiply Strings
- LeetCode Binary Tree Level Order Traversal II
- LeetCode(29)-Plus One
- [Leetcode刷题总结系列][Dynamic Programming]63. Unique Paths II
- LeetCode 第 73 题 (Set Matrix Zeroes)
- 388. [LeetCode]Longest Absolute File Path
- [LeetCode] Path Sum III 二叉树的路径和之三
- [LeetCode]143. Reorder List