zoukankan      html  css  js  c++  java
  • 有环链表的环起点

    用两个指针,一个快指针一次走两步,一个慢指针一次走一步。快慢指针可以重合表示链表有环,此时距离环起点的距离和起点距离环起点的距离相等。

    #include "bits/stdc++.h"
    using namespace std;
    struct List {
        List* next;
    };
    List* beginOfCircle(List* p1, List* p2) {
        while (p1 != p2) {
            p1 = p1->next;
            p2 = p2->next;
        }
        return p1;
    }
    List* hasCircle(List* head) {
        List* fast = head;
        List* slow = head;
        while (slow != NULL && fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                return beginOfCircle(head, slow);
            }
        }
        return NULL;
    }
    List* init() {
        List* rec = (List*)malloc(sizeof(List));
        rec->next = NULL;
    }
    int main() {
        List* head;
        List* ans;
        List* now;
        List* res;
        /*
        head = (List*)malloc(sizeof(List));
        head->next = (List*)malloc(sizeof(List));
        head->next->next = (List*)malloc(sizeof(List));;
        head->next->next->next = (List*)malloc(sizeof(List));
        head->next->next->next = head->next;
        res = hasCircle(head);
        if (res == head->next) {
            puts("YES");
        } else {
            puts("NO");
        }
        */
        int n, m;
        scanf("%d %d", &n, &m);
        head = init();
        now = head;
        while (--n) {
            now->next = init();
            now = now->next;
        }
        ans = now;
        if (m == 0) {
            res = hasCircle(head);
            if (res == ans) {
                puts("YES");
            } else {
                puts("NO");
            }
            return 0;
        }
        while (--m) {
            now->next = init();
            now = now->next;
        }
        now->next = ans;
        res = hasCircle(head);
        if (res == ans) {
            puts("YES");
        } else {
            puts("NO");
        }
        return 0;
    }

    main函数里为验证,可以输入环起点的编号n和一个环的长度m。最后返回的结果等于环起点输出“YES”,当链表中无环的情况下返回NULL输出结果为“NO”;

  • 相关阅读:
    [LeetCode#260]Single Number III
    1 sql server中添加链接服务器
    1 sql server 中cursor的简介
    1 .net将xml反序列化
    1 C# 将对象序列化
    1 SQL SERVER 实现字符串分割成table的方法
    1 asp.net 中如何把用户控件应用于母版页
    1 .net中自定义事件的步骤
    .NET中跨线程访问winform控件的方法
    1 sql server 中merge的用法
  • 原文地址:https://www.cnblogs.com/Angel-Demon/p/10199477.html
Copyright © 2011-2022 走看看