题目
给定一个链表的头节点 head,删除链表的 中间节点 ,并返回修改后链表的头节点。

https://leetcode.cn/problems/delete-the-middle-node-of-a-linked-list/
思路
-
当链表长度为奇数时(如 n=5):
fast走到最后一个节点(fast.next == null)时停止 -
当链表长度为偶数时(如 n=4):
fast走到null时停止 -
此时
slow指向中间节点,preSlow指向中间节点的前一个节点
code
java
/**
* 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 fast=head;
ListNode slow=head;
ListNode preSlow=slow;//删除节点时候要记录删除点的前一个节点
//找中间
while(fast!=null && fast.next!=null){
fast=fast.next.next;
preSlow=slow;
slow=slow.next;
}
preSlow.next=slow.next;//删除
return head;
}
}