【链表】快慢指针的边界问题
在对链表进行操作时我们经常用到快慢指针,针对不同的场景会有不同的边界要求:
- 奇数长度返回中点,偶数长度返回上中点
public static Node upMid(Node head) {
if (head == null) {
return null;
}
Node slow = head;
Node fast = head;
if (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
- 奇数长度返回中点,偶数长度返回下中点
public static Node downMid(Node head) {
if (head == null || head.next == null) {
return head;
}
Node slow = head;
Node fast = head.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow.next;
}
- 奇数长度返回中点前一个,偶数长度返回上中点前一个
public static Node preOfUpMid(Node head) {
if (head == null || head.next == null || head.next.next == null) {
return null;
}
Node slow = head;
Node fast = head.next.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
- 奇数长度返回中点前一个,偶数长度返回下中点前一个
public static Node preOfDownMid(Node head) {
if (head == null || head.next == null) {
return null;
}
Node slow = head;
Node fast = head.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
- 奇数长度返回中点下一个,偶数长度返回上中点下一个
public static Node afterOfUpMid(Node head) {
if (head == null || head.next == null) {
return null;
}
Node slow = head.next;
Node fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
- 奇数长度返回中点下一个,偶数长度返回下中点下一个
public static Node afterOfDownMid(Node head) {
if (head == null || head.next == null || head.next.next == null) {
return null;
}
Node slow = head.next.next;
Node fast = head.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow.next;
}
本文来自博客园,作者:hzyuan,转载请注明原文链接:https://www.cnblogs.com/hzyuan/p/15820508.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)