LeetCode Entry
2095. Delete the Middle Node of a Linked List
Remove the middle of Linked LIst
2095. Delete the Middle Node of a Linked List medium substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1391
Problem TLDR
Remove the middle of Linked LIst
Intuition
- fast & slow pointer
- count, then walk again
Approach
- Rust: fast & slow can be done with unsafe + raw pointers
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
fun deleteMiddle(h: ListNode?) = run {
val d = ListNode(0).apply{next = h}
var s: ListNode? = d; var f = h
while(f?.next!=null){s = s?.next;f=f?.next?.next}
s?.next = s?.next?.next; d.next
}
pub fn delete_middle(mut h: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut cnt = 0; let mut s = &h;
while let Some(n) = &s { s = &n.next; cnt += 1 }
if cnt <= 1 { return None } let mut s = &mut h;
for i in 0..cnt/2-1 { s = &mut s.as_mut().unwrap().next }
let mid = s.as_mut().unwrap().next.take();
s.as_mut().unwrap().next = mid.and_then(|mut n| n.next.take());
h
}
Comments