Delete a node in linked list | Leetcode 237 Java Solution

We are given a singly-linked list and we want to delete a node in it. Access is not given to the first node of the head.

Before looking into below solution it is recommended that you try to solve this problem on your own and then look at the below solution. This would help your problem solving skills!

Deleting the node

Let us take an example of the list

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

Since access is only given to the node to be deleted and here we do not have any access to first node. To delete any node in singly-linked we must have access to it's predecessor. But here we do not have access to the first node to iterate to the predecessor of the node to be deleted

Then how we delete it?

Steps for deleting the node

  1. Let us call pointer to given node to be deleted as A
  2. Get access to the next node of the node to be deleted. Let us call this pointer B
  3. Copy the content of next node(B) to the given node(A). At this stage both the node A and B have same content 2->7->7>10
  4. Move the pointer from the node to be deleted(A) to the next node of B 2->7—->10

Below is the code solution in Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
  */
  class Solution {
  public void deleteNode(ListNode node) {

       ListNode next = node.next;        
       node.val=next.val;
       node.next=next.next;

      }
  }

Hopefully you must have understood the solution to the problem!