阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给定链表头结点 head,链表长度为 n,中间节点下标为
示例:
输入:head = [1,3,4,7,1,2,6] 输出:[1,3,4,1,2,6] 解释:链表长度7,中间下标3,删除值为7的节点。
pre 跟随slow,用于跳过中间节点完成删除操作。package lc2095;
class Solution {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode deleteMiddle(ListNode head) {
if (head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
ListNode last = head;
boolean flag = false;
while (fast.next != null && fast.next.next != null) {
last = slow;
slow = slow.next;
fast = fast.next.next;
if (fast.next == null) {
flag = true;
}
}
if (flag) {
last.next = slow.next;
} else {
if (slow.next != null) {
slow.next = slow.next.next;
} else {
slow.next = null;
}
}
return head;
}
}/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteMiddle(ListNode head) {
// 仅有一个节点,直接返回空
if (head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
// pre保存慢指针的前一个节点,用于删除中间节点
ListNode pre = null;
// 快指针每次两步,慢指针一步,循环至fast到达链表尾部
while (fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
// 跳过中间节点slow,完成删除
pre.next = slow.next;
return head;
}
}