Posts Delete without head pointer (geeksforgeeks - SDE Sheet)
Post
Cancel

Delete without head pointer (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

You are given a node del_node of a Singly Linked List where you have to delete a value of the given node from the linked list but you are not given the head of the list.

geeksforgeeks

SOLUTION

APPROACH

Since head of the linked list is not given, we cannot get to the previous node and then remove the current node. So, the only option is to replace the value of current node with the next nodes and finally get rid of the last node in the linked list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {

    void deleteNode(Node node) {

        Node t = node;

        while(t.next != null){

            t.data = t.next.data;

            // last node that we need
            if(t.next.next == null){
                t.next = null;
                break;
            }

            t = t.next;

        }


    }

}

BETTER APPROACH

We don’t really need to keep iterating over all the nodes to copy over.

We can copy the value from the adjacent node only for the current node and delete the next node!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {

    void deleteNode(Node node) {

        if(node == null || node.next == null)
            return;

        Node nextNode = node.next;
        node.data = nextNode.data;

        node.next = nextNode.next;

    }

}
This post is licensed under CC BY 4.0 by the author.