zoukankan      html  css  js  c++  java
  • Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Note: Do not modify the linked list.

    Follow up:
    Can you solve it without using extra space?

    分析: 判断链表中是否有环比较简单,快慢指针,但是找出环开始节点相对来说比较难,

    my solution is like this: using two pointers, one of them one step at a time. another pointer each take two steps. Suppose the first meet at step k,the length of the Cycle is r. so..2k-k=nr,k=nr
    Now, the distance between the start node of list and the start node of cycle is s. the distance between the start of list and the first meeting node is k(the pointer which wake one step at a time waked k steps).the distance between the start node of cycle and the first meeting node is m, so...s=k-m,
    s=nr-m=(n-1)r+(r-m),here we takes n = 1
    ..so, using one pointer start from the start node of list, another pointer start from the first meeting node, all of them wake one step at a time, the first time they meeting each other is the start of the cycle.

    /**
     * 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) {
            ListNode* p1 =head;
            ListNode* p2 = head;
            bool isCycle = false;
            while(p1&&p2){
                p1 = p1->next;
                if(p2->next == NULL)
                    return NULL;
                p2 = p2->next->next;
                if(p1==p2){
                    isCycle = true;
                    break;
                }
                    
            }
            if(!isCycle) return NULL;
            p1 = head;
            while(p1!=p2){
                p1 = p1->next;
                p2 = p2->next;
            }
            return p1;
        }
    };
  • 相关阅读:
    ThinkPHP Model+数据库的切换使用
    关于SSD安装系统的一些设置(PE安装win 7)
    PHP实现文件下载:header
    Thinkphp 使用PHPExcel导入,栗子
    Ueditor 的使用(这里以php+ci为例)
    js获取鼠标选中的文字内容
    WNMP 下 Nginx 配置 (使用了phpfind一键安装环境)
    javascript 实现 trim
    javascript 获取 CSS 样式表属性
    javascript 删除节点问题
  • 原文地址:https://www.cnblogs.com/willwu/p/6395602.html
Copyright © 2011-2022 走看看