您的位置:首页 > 其它

Linked List Cycle -- leetcode

2015-06-02 16:47 218 查看
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;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: