码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List Cycle

时间:2015-03-15 19:38:56      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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

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

思路:1.两个指针,一个走1步,一个走2步,如果相遇则有环

注意: 在使用p->next时,一定要判断p是否为空。使用p->next->next时,检查p->next是否为空

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

 

Linked List Cycle

标签:

原文地址:http://www.cnblogs.com/renrenbinbin/p/4340229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!