Skip to main content

237. Delete Node in a Linked List

https://leetcode.com/problems/delete-node-in-a-linked-list/

Level: Medium (should be Easy)

Initial Solution

Time: O(n)\mathcal{O}(n)

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
cur = node
next = node.next
while next is not None:
cur.val = next.val
if next.next is None:
cur.next = None
break
cur = next
next = cur.next

Optimized Solution

Time: O(1)\mathcal{O}(1)

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next