Question: Write a main function in Java where it utilizes the insertAfter function. class Node{ int key; Node next; public Node( int data) { key =
Write a main function in Java where it utilizes the insertAfter function.
class Node{
int key;
Node next;
public Node(int data) {
key = data;
next = null;
}
}
class LinkedList{
Node head;
public LinkedList() {
head = null;
}
public boolean isEmpty() {
return head == null;
}
public void insertAtFront(int new_data) {
// create a new node of object type Node
Node new_node = new Node(new_data);
// the next of this node will by the current head node
new_node.next = head;
// the new head will be the new node with the new data
head = new_node;
}
public void insertAtEnd(int new_data) {
Node new_node = new Node(new_data);
// if head is null, make this new node the head and next is null
if(head == null) {
head = new_node;
return;
}
new_node.next = null;
Node last = head;
while(last.next != null) {
last = last.next;
}
last.next = new_node;
return;
}
public void show() {
Node node = head;
while(node.next != null) {
System.out.println(node.key);
node = node.next;
}
System.out.println(node.key);
}
public void insertAfter(Node prev_node, int new_data) {
if(prev_node == null) {
System.out.println("The given previous node cannot be null!");
return;
}
Node new_node = new Node(new_data);
new_node.next = prev_node.next;
prev_node.next = new_node;
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
