Question: import java.util.Scanner; class IntNode { int data; IntNode next; IntNode ( int data ) { this.data = data; this.next = null; } void insertAfter (

import java.util.Scanner;
class IntNode {
int data;
IntNode next;
IntNode(int data){
this.data = data;
this.next = null;
}
void insertAfter(IntNode newNode){
newNode.next = this.next;
this.next = newNode;
}
}
public class LabProgram {
// Recursive method to print linked list
public static void printLinkedList(IntNode head){
// Base case: if head is null, return
if (head == null){
System.out.println();
return;
} else {
// Print current node's data
System.out.print(head.data);
// If next node is not null, print comma
if (head.next != null){
System.out.print(",");
}
// Call printLinkedList recursively with next node
printLinkedList(head.next);
}
}
public static void main(String[] args){
Scanner scnr = new Scanner(System.in);
int size = scnr.nextInt();
int value = scnr.nextInt();
IntNode headNode = new IntNode(value); // Make head node as the first node
IntNode lastNode = headNode; // Node to add after
IntNode newNode = null; // Node to create
// Insert the second and the rest of the nodes
for (int n =0; n < size -1; ++n){
value = scnr.nextInt();
newNode = new IntNode(value);
lastNode.insertAfter(newNode);
lastNode = newNode;
}
// Call printLinkedList() with the head node
printLinkedList(headNode);
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!