• 链表中环的入口结点-剑指Offer


    链表中环的入口结点

    题目描述

    一个链表中包含环,请找出该链表的环的入口结点。

    思路

    1. 若该链表存在环,设置两个指针pSlow和pFast,pSlow每次走一步,pFast每次走两步,当pFast追上pSlow的时候,pFast比pSlow多走的正好是pSlow走的也就是环所包含的节点的个数。
    2. 所以,第二次走,一个从头结点开始,另一个从相遇节点开始,最终会在环的入口节点相遇

    代码

    /*
     public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }
    */
    public class Solution {
    
        public ListNode EntryNodeOfLoop(ListNode pHead)
        {
            if (pHead == null) {
            	return null;
            }
    		ListNode pSlow = pHead;
    		ListNode pFast = pHead;
    		do {
    			if (pFast.next == null) {
    				return null; // 有空值说明改链表没有环
    			}
    			pSlow = pSlow.next;
    			pFast = pFast.next;
    			if (pFast.next == null) {
    				return null; // 有空值说明改链表没有环
    			}
    			pFast = pFast.next;
    		} while (pSlow != pFast);
    		pSlow = pHead;
    		while (pSlow != pFast) {
    			pSlow = pSlow.next;
    			pFast = pFast.next;
    		}
    		return pSlow;
        }
    }
  • 相关阅读:
    File类
    Java运算符
    JAVA语法
    数据库-子查询
    爬取笔趣阁_完本书籍
    爬取动物图片源码
    爬取电影天堂上最新电影的下载链接的源码
    pyinstaller的安装、使用、出错解决办法
    Emmet插件使用方法总结
    Markdown基本语法
  • 原文地址:https://www.cnblogs.com/rosending/p/5693155.html
Copyright © 2020-2023  润新知