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.

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

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if (head==null) {
                return null;
            }
            ListNode pFast = head;
            ListNode pSlow = head;
            boolean first = true;
            while (pFast != null) {
                if (pSlow == pFast && !first) {
                    //从相遇点找入口
                    ListNode p = head;
                    while (p!=null) {
                        if(p==pFast) {
                            return p;
                        }
                        p = p.next;
                        pFast = pFast.next;
                    }
                }
                pSlow = pSlow.next;
                if (pFast.next !=null) {
                    pFast = pFast.next.next;
                } else {
                    pFast = null;
                }
                first = false;
            }
            return null;
        }
    }
  • 相关阅读:
    智联招聘
    我的Linux以及软件配置(长期更新)
    关于Git的笔记
    PHP和HTML表单
    web学习笔记——CSS整理(一)
    新开通博客园
    Thinphp模板替换
    __APP__
    大步前行
    centos 7 添加环境变量
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506834.html
Copyright © 2011-2022 走看看