leetcode经典例题(详细思路及代码注释)

本文详细解析了LeetCode中关于链表的几道经典题目,包括判断链表是否有环、找到环的起始节点、寻找两个链表的交点、删除链表的倒数第n个节点、反转链表以及合并两个有序链表等。通过示例代码和思路分析,帮助读者深入理解链表操作和算法实现。
摘要由CSDN通过智能技术生成

141.给定一个链表,判断链表中是否有环。
public class Solution {
public boolean hasCycle(ListNode head) {
if(headnull||head.nextnull){ //若链表为空,或链表中只有一个元素,则一定无环;
return false;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null&& fast.next!=null){ //当fast和fast.next 不为空,slow向后移动一步,fast向后移动两步
slow=slow.next;
fast=fast.next.next;
if(slow==fast){ //当fast和slow重合时候,成环;
return true;
}
}
return false;
}
}
142.给定一个链表,返回链表中第一个入环的节点,若没有环,返回null;

public class Solution {
public ListNode detectCycle(ListNode head) {
if(headnull||head.nextnull){
return null;
}
ListNode fast=head;
ListNode slow=head;
while(fast !=null&&fast.next!=null){ //如果链表中存在元素,fast和slow分别后移
fast=fast.next.next;
slow=slow.next;
if(fastslow){ //如果重合,则成环跳出
break;
}
}
if(fast
null||fast.nextnull){ //如果链表为,返回null
return null;
}
while(fast!=head){
fast=fast.next;
head=head.next;
}
return fast;
}
}
160.给定两个链表,判断两个链表是否有交点。
思路:设置两个指针p1和p2.
p1从 headA 开始,p2从 headB 开始;
p1 p2分别从表头开始每次向后移动一个节点,移动到末尾处时,再换一个链表从头向后移动,如果p1=p2,则证明有交点,否则返回null;

代码如下:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headAnull||headBnull){
return null;
}
ListNode p1=headA; //p1 从headA 开始向后移动
ListNode p2=headB; //p2从headB开始向后移动
boolean isp1Change=false; //定义换向时候的布尔变量
boolean isp2Change=false;
while(p1!=null||p2!=null){
if(p1
p2){
return p1;//或者p2
}
p1=p1.next;
p2=p2.next;
if(isp1Change&&isp2Change&&p1null&&p2null){ //如果换向后走完了,则代表没有交点。
break;
}
i

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值