Program opened below. You can scroll through the algorithm, Java code and output.
Program 53
Insert an Element at the Rear of a Linked List
Question
Create a singly linked list, insert a new node at the rear and display the resulting list.
Algorithm
Step 1: Start the program and create the first node of the linked list.
Step 2: Accept the data for the first node and set its link to null.
Step 3: Accept the number of additional nodes to create.
Step 4: Create each additional node and accept its data.
Step 5: Link each new node to the last node already in the list.
Step 6: After the initial list has been created, display the list if required.
Step 7: Accept the value to be inserted at the rear.
Step 8: Create a new node containing that value.
Step 9: Set the new node's link to null.
Step 10: Set a traversal pointer to the first node.
Step 11: Move the pointer forward while its link is not null.
Step 12: Link the last node to the new node.
Step 13: Traverse and display every node on a separate line, then stop.
Java program
Javaimport java.util.*;
class InsertRear
{
static class Node
{
int data;
Node next;
Node(int value)
{
data = value;
next = null;
}
}
Node head = null;
void insertRear(int value)
{
Node fresh = new Node(value);
if (head == null)
{
head = fresh;
}
else
{
Node ptr = head;
while (ptr.next != null)
{
ptr = ptr.next;
}
ptr.next = fresh;
}
}
void display()
{
Node ptr = head;
System.out.println("Linked list:");
while (ptr != null)
{
System.out.println(ptr.data);
ptr = ptr.next;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
InsertRear list = new InsertRear();
System.out.print("Number of initial nodes: ");
int n = sc.nextInt();
for (int i = 1; i <= n; i++)
{
System.out.print("Enter data: ");
list.insertRear(sc.nextInt());
}
System.out.print("Value to insert at rear: ");
int value = sc.nextInt();
list.insertRear(value);
list.display();
}
}Sample output
Input: Initial values: 10, 20, 30; value to insert: 40
Output: Linked list:
10
20
30
40