Problem
You are given the head
of a linked list. Delete the middle node, and return the head
of the modified linked list.
The middle node of a linked list of size n
is the ⌊n / 2⌋th
node from the start using 0-based indexing, where ⌊x⌋
denotes the largest integer less than or equal to x
.
- For
n
=1
,2
,3
,4
, and5
, the middle nodes are0
,1
,1
,2
, and2
, respectively.
Examples
Example 1:
graph LR; A(1) --> B(3) --> C(4) --> D(7) --> E(1) --> F(2) --> G(6) style D fill:#f9f
|
|
Example 2:
graph LR; A(1) --> B(2) --> C(3) --> D(4) style C fill:#f9f
|
|
Example 3:
graph LR; A(2) --> B(1) style B fill:#f9f
|
|
Solution
Method 1 - Two Pass - First find length of list and then go to middle
We first calculate the length of the linked list using Find the length of the linked list, lets call it n
. Then loop till n/2
and remove the n/2
th node.
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the linked list. - 🧺 Space complexity:
O(1)
Method 2 - Slow and Fast Pointer
This problem is similar to Middle of the linked list, but here we need to modify the list, so we need prev pointer, and hence we need dummy
pointer.
We can follow following steps:
- Create a
dummy
head, and initializeslow
andfast
pointers asdummy
; - Traverse the ListNodes starting from
dummy
by the afore-mentioned two pointers,slow
forwards1
step andfast
forwards2
steps per iteration; - Terminate the traversal till
fast.next
orfast.next.next
isnull
, and nowslow
points to the previous node of themiddle
node; remove themiddle
node; - Return
dummy.next
as the result.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the linked list. - 🧺 Space complexity:
O(1)
Method 3 - Slow and Fast with prev pointer
Add a prev
pointers following slow
one.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the linked list. - 🧺 Space complexity:
O(1)