Leetcode Linked List Cycle

Leetcode Linked List Cycle ,本算法主要检测单链表中的环,算法要求O(1)的空间。本算法通过以不同的步长进行检测,如果步长大于环长,则一定可以验测到环,算法时间复杂度O(n),相关代码如下:

#include<iostream>
#include<vector>

using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
/*
 * Each step we traves 2^k element in the linked list, if there is a node
 * equals to the anchor node, there is a cycle in the linked list.
 * And the time spend is O(2n), and space spend is O(1).
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head) {
            return false;
        }
        int inc = 1;
        ListNode* anchor = head;
        ListNode* cur = head->next == NULL? NULL: head->next;
        while (cur) {
            anchor = cur;
            // Scan the list find the equals one
            for (int i = 0; i < inc && cur; i ++) {
                cur = cur->next;
                if (cur == anchor) {
                    return true;
                }
            }
            inc *= 2;
        }
        return false;
    }
};

// Sample input: ./a.out argv1 argv2 ...
int main(int argc, char* argv[]) {
    Solution so;
    vector<string> test;
    ListNode* head = NULL;
    ListNode* cur = NULL;
    // Make the test linked list
    for (int i = 1; i < argc; i ++) {
        if (cur) {
            cur->next = new ListNode(atoi(argv[i]));
            cur = cur->next;
        } else {
            cur = new ListNode(atoi(argv[i]));
            head = cur;
        }
    }
    cur->next = head;
    bool re = so.hasCycle(head);
    cout<<"resutl: "<<re<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值