I'm trying to delete the last node of the linkedlist, given pointer only to that node.
I wrote the below implementation, but isn't working.
I already visited majority of SO questions regarding this subject, but none of them shows how to delete last node of linked list, if there's only one pointer to that node ?
Am I missing anything here ?
class Node {
Node next;
int value;
Node(int val) {
this.value = val;
this.next = null;
}
@Override
public String toString() {
Node cur = this;
String str = "";
while(cur != null) {
str += cur.value+"->";
cur = cur.next;
}
return str;
}
}
class DeleteNodeLL {
public static void deleteNode(Node current) {
Node temp;
if(current.next == null) {
current = null;
return;
} else {
current.value = current.next.value;
temp = current.next;
temp = null;
current.next = current.next.next;
}
}
public static void main(String [] args) {
Node n1 = new Node(25);
Node n2 = new Node(1);
Node n3 = new Node(36);
Node n4 = new Node(9);
Node n5 = new Node(14);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = null;
System.out.println("Original linkedlist :");
System.out.println(n1);
System.out.println();
System.out.println("After deleting a node :");
deleteNode(n5);
System.out.println(n1);
}
}
Output :-
Original linkedlist :
25->1->36->9->14->After deleting a node :
25->1->36->9->14->
With the singly linked list it is not possible.
This is the interview questions which is typically asked in Big Shot companies which emphasizes on Data Structures.
The question is formulated as "Delete the node in single linked list given pointer to only that node"
Expected Solution:
public void deleteNode(Node n)
{
if(n==null || n.next==null)
{
System.out.println("Delete not possible");
return;
}
n.data = n.next.data;
Node tmp = n.next;
n.next = n.next.next;
tmp.next = null;
System.out.println("Node Deleted");
}
The idea is to copy the data from the next node to the current node and delete the next node. The solution does not work if the node is the last node (This is what candidate has to debate and point out in interview)
Hope it helps you! (Solution to your problem is a trick question, and it does not exists)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With