In: Computer Science
In java please create a method that will insert a value after a specific node for a linked list.
public void insertAfter(Node a, int newData){
}
public class LinkedList {
Node head; //head of
the list
class Node //Linked
List Node
{
int data;
Node next;
Node(int d) {
data=d; //store value
next=null; //stores address of the next value
}
}
// Appends a new node in the linked list similar to
incremental fashion.
public void append(int new_data)
{
//Allocate the node and set and
data and next as null
Node new_node = new
Node(new_data);
//If the Linked List is empty, then
make the new node as head
if(head == null) {
head = new
Node(new_data);
return;
}
// make the next of new node as
null since its going to be the last element in the list
new_node.next=null;
//Else traverse till the last node,
and find the last element.
Node last= head;
while(last.next != null)
last=last.next;
// point the last node to new node
by changing the next of last node.
last.next=new_node;
return;
}
// Inserts a new node after the given previous
node.
public void insertAfter(Node a, int newData)
{
//First check whether given node is
null or not
if(a == null) {
System.out.println("The given Previous node cannot be null so enter
value in the LinkedList");
return;
}
//Else we gonna Allocate the Node
and insert the data into the linkedlist
Node new_node= new
Node(newData);
// make next of new Node as next of
previous node
new_node.next= a.next;
// make next of previous node as
new node
a.next=new_node;
}
//This function prints the contents of linked list
starting from head
public void printList()
{
Node node= head;
while(node!=null) //
while linked list has node
{
System.out.print(node.data+" "); //print the data
node=node.next;
//increment the next
}
}
public static void main(String[] args) {
// Start with the empty
list
LinkedList llist = new LinkedList();
// Insert node 5,3,8,9 into the linkedlist
llist.append(5);
llist.append(3);
llist.append(8);
llist.append(9);
System.out.print("Linked List is : ");
llist.printList();
System.out.println();
// Insert 4, after 8. So linked list becomes
// 5->3>8->4->9->Nulllist
llist.insertAfter(llist.head.next.next, 4); //prev node is
head->next-next= 8
System.out.print("After Inserting New Node After
"+llist.head.next.next.data+" : ");
llist.printList();
}
}
Output: // Please appreciate my answer if it was helpful. If you have any doubts feel free to add comments. Thanks in advance.