**一. 題目描述**
Given a linked list, determine if it has a cycle in it.?
Follow up: Can you solve it without using extra space?
**二. 題目分析**
題目的意思是給定一個鏈表的頭指針,快速判斷一個鏈表是不是有環,如果有環,返回環的起始位置。該題的經典做法是使用兩個指針,兩個指針均指向頭結點,其中一個是快指針,一次走兩步;另一個是慢指針,一次只走一步,當兩個指針相遇時,證明有環。這種方法的時間復雜度為`O(n)`,空間復雜度`O(1)`,這里需要考慮一些特殊情況:
* 空鏈表無環
* 鏈表只有一個節點時可能構成自環
**三. 示例代碼**
~~~
#include <iostream>
struct ListNode
{
int value;
ListNode* next;
ListNode(int x) :value(x), next(NULL){}
};
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
return false;
ListNode* fast = head;
ListNode* slow = head;
while (fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow) return true;
}
return false;
}
};
~~~
鏈表只有一個節點且該節點構成自環:

鏈表3->4->5->6->7,4->5->6->7形成環:

**四. 小結**
關于有環鏈表中快慢指針一定會相遇的解決方法,可以簡單地證明:
如果有環的話,快慢指針都會進入有環的部分。
而一旦進入有環的部分,一快一慢,學過物理都知道,其實可以相當于一個靜止另一個每次移動一格。
到此,為什么一定會相遇應該已經很明顯了吧~
該方法廣為人知,不知是否有更為精妙的解法?
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016騰訊軟件開發筆試題)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契數列問題)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波蘭式的計算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和問題)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching