• leetcode 141 142. Linked List Cycle


    题目描述:

    不用辅助空间判断,链表中是否有环

    /**
     * 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) {
            if(head == NULL)
                return false;
            ListNode *first = head;
            ListNode *Second = head;
            while(Second->next != NULL){
                
                first = first->next;
                Second = Second->next->next;
                if(Second == NULL)
                    return false;
                if(Second == first)
                    return true;
            }
            return false;
        }
    };

    142  找到环开始的结点

    第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。

    因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            if(head == NULL)
                return NULL;
            ListNode *first = head;
            ListNode *second = head;
            bool flag = true;
            while(second->next != NULL){
                first = first->next;
                second = second->next->next;
                if(second == NULL)
                    return NULL;
                if(first == second){
                    flag = false;
                    break;
                }
            }
            if(flag == true)
                return NULL;
            first = head;
            while(first != second){
                first = first->next;
                second = second->next;
            }
            return first;
            
        }
    };
  • 相关阅读:
    火爆全网的合成大西瓜小游戏魔改版大全
    [Qt]cmake下Qt隐藏console的窗口
    c# WebBrowser控制台输出执行js后的网页内容
    好的编程习惯是减少bug最有效的方法
    创建线程 出现SIGSEGV crash
    linux下进程创建/僵尸进程/孤儿进程
    C++实现不可被继承的类
    程序并发概述
    C++ vector实现原理
    C++深拷贝和浅拷贝
  • 原文地址:https://www.cnblogs.com/strongYaYa/p/6780082.html
Copyright © 2020-2023  润新知