Delete Node in a Linked List

Monisha Mathew
1 min readJul 15, 2019

--

Question: Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

You may view the full question here.

Approach 1: Well, this question was a puzzler. The usual approach would be to alter the ‘next’ pointer in the previous node. We would skip the node to be deleted and instead make the previous node directly point to the next node that follows.

Considering that this is a singly linked list, and that we have access to only the one node that we will have to delete, the usual approach discussed above will not work for us. I confess, had to take a peek at the solution mentioned here.

//Approach 1:
//Runtime: 0ms
//Memory usage: 36.8MB
/**
* 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 curr = node;
node = node.next;
while(node!=null){
curr.val = node.val;
if(node.next != null){
curr = node;
} else {
curr.next = null;
}
node = node.next;
}
}
}

Find more posts here.

Cheers & Chao!

--

--