141. Linked List Cycle

1. 问题描述

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Tags: Linked List Two Pointers
Similar Problems: (M) Linked List Cycle II

2. 解题思路

  • 画图分析,发现规律,两个指针(*pF 步长为1,*pS步长为2)

3. 代码

class Solution {
public:
    bool hasCycle(ListNode *head) 
    {
        if (!head)
        {
            return false;
        }
        ListNode *pF = head;
        ListNode *pS = head;
        while (pS->next)
        {
            pS = pS->next;
            if (pS == pF)
            {
                return true;
            }
            pS = pS->next;
            if (!pS)
            {
                return false;
            }
            pF = pF->next;
        }
        return false;
    }
};

4. 反思

posted on 2016-08-08 23:34  whl-hl  阅读(102)  评论(0编辑  收藏  举报

导航