当前位置:网站首页>LeetCode链表问题——142.环形链表II(一题一文学会链表)
LeetCode链表问题——142.环形链表II(一题一文学会链表)
2022-07-28 19:46:00 【十八岁讨厌Java】
一、题目描述:
难度中等1688收藏分享切换为英文接收动态反馈
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。

二、代码
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {// 有环
ListNode index1 = fast;
ListNode index2 = head;
// 两个指针,从头结点和相遇结点,各走一步,直到相遇,相遇点即为环入口
while (index1 != index2) {
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}三、了解链表
什么是链表,链表是一种通过指针串联在一起的线性结构,每一个节点由两部分组成,一个是数据域一个是指针域(存放指向下一个节点的指针),最后一个节点的指针域指向null(空指针的意思)。链接的入口节点称为链表的头结点也就是head。
单链表:
双链表:
每一个节点有两个指针域,一个指向下一个节点,一个指向上一个节点。
双链表 既可以向前查询也可以向后查询。

循环链表:
循环链表,顾名思义,就是链表首尾相连。循环链表可以用来解决约瑟夫环问题。

链表的存储方式:
数组是在内存中是连续分布的,但是链表在内存中可不是连续分布的。
链表是通过指针域的指针链接在内存中各个节点。
所以链表中的节点在内存中不是连续分布的 ,而是散乱分布在内存中的某地址上,分配机制取决于操作系统的内存管理。
删除节点:
只要将C节点的next指针 指向E节点就可以了。

添加节点:

与数组对比:

边栏推荐
猜你喜欢

云安全核心技术
![[tidb] importing TXT documents into the database is really efficient](/img/2a/d33849987a75c4a0d52d8f0ab767ca.png)
[tidb] importing TXT documents into the database is really efficient

Study and use of cobalt strike
![[input ID number] is replaced by an asterisk, and input is cut into multiple small squares (similar)](/img/f0/7e3ea94e02a42b6055c40b58d1e39c.png)
[input ID number] is replaced by an asterisk, and input is cut into multiple small squares (similar)

ICML2022 | 时序自监督视频transformer

Maxwell is an easy-to-use software for capturing MySQL data in real time

九鑫智能正式加入openGauss社区

Quii Cordova plugin telerik imagepicker plug-in multi image upload out of sequence

到底为什么不建议使用SELECT * ?

Moco V1: the visual field can also be self supervised
随机推荐
MySQL
Redis cache avalanche, cache penetration, cache breakdown
Introduction to blue team: efficiency tools
(转)冒泡排序及优化详解
System integration under microservice architecture
工业通讯领域的总线、协议、规范、接口、数据采集与控制系统
Learning typescript (II)
Confession of a graduate student: why am I addicted to opengauss community?
The framing efficiency of setpreviewcallbackwithbuffer will become lower
Ctfshow question making web module web11~web14
(turn) bubble sorting and optimization details
多线程顺序运行的 4 种方法,面试随便问
Buuctf questions upload labs record pass-11~pass-20
Several skills of API interface optimization
Capture video by buffering
What functions does MySQL have? Don't look everywhere. Just look at this.
Young freshmen yearn for more open source | here comes the escape guide from open source to employment!
4.1 various calling methods of member
ICML2022 | 时序自监督视频transformer
How to measure software architecture