Delete the Middle Node of a Linked List — LeetCode 2095 Python Solution
MediumLinked ListTwo Pointers
- Problem
- #2095
- Pattern
- Linked List
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.
Example
- Input
- head = [1,3,4,7,1,2,6]
- Output
- [1,3,4,1,2,6]
- Explanation
- The above figure represents the given linked list. The indices of the nodes are written below.
Python solution
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]:
dummy = ListNode(next=head)
slow, fast = dummy, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
slow.next = slow.next.next
return dummy.nextComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the list |
| Space | O(1) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 2095. Delete the Middle Node of a Linked List is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 2095. Delete the Middle Node of a Linked List?
- LeetCode 2095. Delete the Middle Node of a Linked List is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2095. Delete the Middle Node of a Linked List?
- The Python solution on this page runs in O(n), where n is the length of the list.
- What is the space complexity of LeetCode 2095. Delete the Middle Node of a Linked List?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2095. Delete the Middle Node of a Linked List cover?
- LeetCode 2095. Delete the Middle Node of a Linked List is tagged Linked List and Two Pointers on LeetCode.