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

Linked List Cycle -- leetcode

时间:2015-06-02 17:57:11      阅读:89      评论: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?

基本思路:

快慢两指针。

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

/**
 * 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

标签:leetcode   指针      

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

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