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

LeetCode: Linked List Cycle [141]

时间:2014-06-29 22:51:33      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】

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],布布扣,bubuko.com

LeetCode: Linked List Cycle [141]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/35596851

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