Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
Example:
Input: the node c from the linked list a->b->c->d->e->f
Output: nothing is returned, but the new linked list looks like a->b->d->e->f
Solutions
Solution 1: Node Assignment
We can replace the value of the current node with the value of the next node, and then delete the next node. This way, we can achieve the purpose of deleting the current node.
The time complexity is $O(1)$, and the space complexity is $O(1)$.
1 2 3 4 5 6 7 8 91011
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution:defdeleteNode(self,node):node.val=node.next.valnode.next=node.next.next
1 2 3 4 5 6 7 8 91011121314
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */classSolution{publicvoiddeleteNode(ListNodenode){node.val=node.next.val;node.next=node.next.next;}}
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcdeleteNode(node*ListNode){node.Val=node.Next.Valnode.Next=node.Next.Next}
1 2 3 4 5 6 7 8 9101112131415
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } *//** * @param {ListNode} node * @return {void} Do not return anything, modify node in-place instead. */vardeleteNode=function(node){node.val=node.next.val;node.next=node.next.next;};
1 2 3 4 5 6 7 8 91011121314151617
/*** public class ListNode {* var val: Int* var next: ListNode?* init(_ x: Int) {* self.val = x* self.next = nil* }* }*/classSolution{funcdeleteNode(_node:ListNode?){guardletnode=node,letnext=node.nextelse{return}node.val=next.valnode.next=next.next}}