Given the head of a linked list head
and an index i
, delete the ith element, and return the new head of the linked list.
The index will always be in bounds.
Example:
Here's an example linked list:
To delete an element, you can make the pointers "skip over" it. For example, here's how you delete the 2nd element:
The LinkedList acts as if the 2nd node was deleted, because the 1st node points to the 3rd node. And Python will automatically delete the 2nd node when it realizes it's no longer used.
In general, you can delete the i
th element by pointing the i-1
th element to the i+1
th element.
Here's the code for this:
This code usually works, but it breaks when i=0
. This is because the code is supposed to step to the previous node i-1
, but there is no previous node in that case.
To fix this, you can handle this case separately from the other cases. You should return the head.next
node, like this:
Here's the full code for this problem:
Time Complexity O(n). You step through every node in the Linked List.
Space Complexity O(1). You store a single variable called node
.
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()