Delete Node in a Linked List LeetCode Solution

Here, We see Delete Node in a Linked List problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Delete Node in a Linked List LeetCode Solution

Delete Node in a Linked List LeetCode Solution

Problem Statement ->

There is a singly-linked list head and we want to delete a node in it.

You are given the node to be deleted node. You will not be given access to the first node of head.

All the values of the linked list are unique, and it is guaranteed that the given node is not the last node in the linked list.

Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:

  • The value of the given node should not exist in the linked list.
  • The number of nodes in the linked list should decrease by one.
  • All the values before node should be in the same order.
  • All the values after node should be in the same order.
Delete Node in a Linked List example1
fig-1
Example 1: (fig-1)

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Delete Node in a Linked List example2
fig-2
Example 2: (fig-2)

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Delete Node in a Linked List Leetcode Solution C++ ->

class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        node->next = node->next->next;
    }
};
Code language: C++ (cpp)

Delete Node in a Linked List Leetcode Solution Java ->

class Solution {
    public void deleteNode(ListNode node) {
        if(node != null && node.next != null) {
                node.val = node.next.val;
                node.next = node.next.next;
            }
    }
}
Code language: Java (java)

Delete Node in a Linked List Leetcode Solution JavaScript ->

var deleteNode = function(node) {
    node = Object.assign(node, node.next);
	// Let JS GC automaticlly release victimNode in the background
    node = null;
	return;
};
Code language: JavaScript (javascript)

Delete Node in a Linked List Leetcode Solution Python ->

class Solution(object):
    def deleteNode(self, node):
        node.val=node.next.val
        node.next=node.next.next
Code language: Python (python)
Scroll to Top