首页 > 代码库 > LeetCode: Linked List Cycle [141]

LeetCode: Linked List Cycle [141]

【题目】

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?


【题意】

    推断一个单向链表是否有环


【思路】

    维护两个指针p1和p2,p1每次向前移动一步,p2每次向前移动两步
    假设p2可以追上p1,则说明链表中存在环


【代码】

/**
 * 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*p1=head;
        ListNode*p2=head;
        while(p2){
            //p1向前走一步
            p1=p1->next;
            //p2向前走两部
            p2=p2->next;
            if(p2)p2=p2->next;
            //推断p2是否追上了p1
            if(p2 && p2==p1)return true;
        }
        return false;
    }
};


LeetCode: Linked List Cycle [141]