当前位置: 首页 > news >正文

【Hot100】LeetCode—142. 环形链表 II

目录

  • 1- 思路
    • 快慢指针+推导
  • 2- 实现
    • ⭐142. 环形链表 II——题解思路
  • 3- ACM 实现


  • 原题连接:141. 环形链表

1- 思路

快慢指针+推导

  • ① 利用快慢指针,定位环
  • ② 根据环,从头出发一个指针,从环处出发一个指针
    • 两者相遇的地方就是环的入口

2- 实现

⭐142. 环形链表 II——题解思路

在这里插入图片描述

public class Solution {public ListNode detectCycle(ListNode head) {if(head==null){return head;}ListNode slow = head;ListNode fast = head;while(fast.next!=null && fast.next.next!=null){slow = slow.next;fast = fast.next.next;if(slow==fast){ListNode index1 = head;ListNode index2 = slow;while(index1!=index2){index1 = index1.next;index2 = index2.next;}return index1;}}return null;}   
}

3- ACM 实现

public class hashCycle {public static class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}public static ListNode detectCycle(ListNode head) {if(head==null){return head;}ListNode slow = head;ListNode fast = head;while(fast.next!=null && fast.next.next!=null){slow = slow.next;fast = fast.next.next;if(slow==fast){ListNode index1 = head;ListNode index2 = slow;while(index1!=index2){index1 = index1.next;index2 = index2.next;}return index1;}}return null;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("输入链表长度");int n = sc.nextInt();ListNode head = null,tail=null;for(int i = 0 ; i < n;i++){ListNode nowNode  = new ListNode(sc.nextInt());if(head==null){head = nowNode;tail = nowNode;}else{tail.next = nowNode;tail = nowNode;}}System.out.println("输入环的位置");int index = sc.nextInt();ListNode cycleNode = head;while (index>0){cycleNode = cycleNode.next;index--;}tail.next = cycleNode;System.out.println("结果是"+detectCycle(head).val);}
}

http://www.mrgr.cn/news/138.html

相关文章:

  • Go环境搭建-开发工具
  • 容器使用私钥远程至宿主机执行命令
  • Unity 求坐标点在扇形区域内的投影
  • 选择Linux发行版:就像选宠物,你准备好了吗?
  • 不同路径 II[中等]
  • Kali Linux 命令大全
  • C/C++ 不定参函数
  • 模拟实现简单栈和队列
  • RabbitMQ-消息队列延迟队列一
  • 精度±0.1g火试金自动化系统中的失重秤如何为冶金行业带来革命性提升
  • 加密软件怎么保证文件在外发中不会泄露
  • Mac系统如何下载安装Photoshop软件mac的新版指南!
  • [卷积神经网络]YOLOv10论文解读
  • 大模型面试问题记录
  • 日常问题笔记1
  • 关于Qt的系统总结
  • Linux学习记录(十一)———进程间的通信(消息队列)
  • 鸿蒙(API 12 Beta3版)【分段式拍照】媒体相机开发指导(ArkTS)
  • QT的基础数据类型(上)
  • Oracle之触发器