---
# System prepended metadata

title: 2095. Delete the Middle Node of a Linked List

---

# 2095. Delete the Middle Node of a Linked List

https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/


## 思路：
1. 注意邊界問題
2. 可以follow up 使用fast slow pointer  


```python=
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        size=0 
        current= head 
        while current: 
            size+=1 
            current=current.next 
        
        position=(size//2)-1 
        
        current_2=head 
        count= 0 
        
        if size==1: 
            return None 
        
        while count!= position: 
            current_2 =current_2.next 
            count+=1 
        current_2.next=current_2.next.next 
        
        return head 
            
            
            
            
            
```


## follow up 快慢指針法

思路：
1. 因為快指針會跑兩倍快比起慢指針，所以慢指針會還在正中央，當快指針已經到了最尾端的時候。
2. 所以我們需要再存一個節點pre，指向slow 慢指針的前一個，因為我們要去掉slow pointer 正指上的節點。


```python=
 pre,slow,fast =None, head,head 
        
        while fast and fast.next:
            pre=slow 
            slow=slow.next 
            fast=fast.next.next 
            
        if pre ==None:
            return None
        pre.next =slow.next 
        return head 
            
```
