zoukankan      html  css  js  c++  java
  • 142 Linked List Cycle II 环形链表 II

    给一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
    说明:不应修改给定的链表。
    补充:
    你是否可以不用额外空间解决此题?
    详见:https://leetcode.com/problems/linked-list-cycle-ii/description/

    Java实现:

    /**
     * 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) {
            if(head==null){
                return null;
            }
            ListNode slow=head;
            ListNode fast=head;
            while(fast!=null&&fast.next!=null){
                slow=slow.next;
                fast=fast.next.next;
                if(slow==fast){
                    fast=head;
                    while(slow!=fast){
                        slow=slow.next;
                        fast=fast.next;
                    }
                    return slow;
                }
            }
            return null;
        }
    }
    
  • 相关阅读:
    BM&EXCRT
    杨丰磊
    poj3613 Cow Relays
    详解KMP算法
    信息学作文
    恐怖的奴隶主(bob)
    玩具(toy)
    杯子 (glass)
    P3916 图的遍历
    《上帝给我一个任务,叫我牵一只蜗牛去散步》
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8724890.html
Copyright © 2011-2022 走看看