首页 > 其他 > 详细

Linked List Cycle -- leetcode

时间:2015-06-02 17:54:26      阅读:94      评论:0      收藏:0      [点我收藏+]

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

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

基本思路:

快慢两指针。

一个指针每次移动一步,另一个指针每次移动两步。如存在环,必有相遇的时候。

/**
 * 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 *one = head;
        ListNode *two = head;
        while (two && two->next) {
            one = one->next;
            two = two->next;
            two = two->next;
            
            if (one == two)
                return true;
        }
        return false;
    }
};


Linked List Cycle -- leetcode

原文:http://blog.csdn.net/elton_xiao/article/details/46332007

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!