141. Linked List Cycle

来源:互联网 发布:淘宝人工客服在哪里 编辑:程序博客网 时间:2024/06/05 16:19

题目:Linked List Cycle

原题链接:https://leetcode.com/problems/linked-list-cycle/
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和p2最终都会进入环中,由于两者的速度不一样,那么经过若干次的循环,p1和p2一定会重新碰到。

代码如下:

/** * 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) {        if(head == NULL || head->next == NULL) return false;        ListNode* p1 = head, *p2 = head->next->next;        while(p2 && p2->next) {            if(p2 == p1) return true;            p1 = p1->next;            p2 = p2->next->next;        }        return false;    }};
0 0