2095. Delete the Middle Node of A Linked List #
题目 #
给定链表头节点head
,删除链表的中间节点,并返回修改后的链表头节点head
。
长度为 n
链表的中间节点是从头数起第 ⌊n / 2⌋
个节点(下标从 0 开始),其中 ⌊x⌋
表示小于或等于 x
的最大整数。
思路 #
代码 #
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 == null) return null;
ListNode sentinel = new ListNode(-1, head);
ListNode middle = sentinel, fast = sentinel;
while (fast != null && fast.next != null) {
middle = middle.next;
fast = fast.next.next;
}
if (fast != null) middle = middle.next;
ListNode ptr = sentinel;
while (ptr.next != middle) ptr = ptr.next;
ptr.next = middle.next;
return sentinel.next;
}
}