Program opened below. You can scroll through the algorithm, Java code and output.

Delete an Element at the Rear of a Linked List

Download .java

Question

Create a singly linked list, delete the rear node and display the resulting list.

Step 1: Start the program and create a singly linked list. Step 2: Accept the data for each node and link the nodes in sequence. Step 3: Set a pointer to the first node. Step 4: If the first node is null, report that the list is empty. Step 5: If the first node has no next node, set the head to null to delete the only node. Step 6: Otherwise move the pointer until its next node is the last node. Step 7: Set the next reference of the current node to null. Step 8: This disconnects the last node from the list. Step 9: Set the traversal pointer back to the first node. Step 10: Visit each remaining node in order. Step 11: Display each node's data on a separate line. Step 12: Stop the program.
Java
import java.util.*;

class DeleteRear
{
    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 deleteRear()
    {
        if (head == null)
        {
            System.out.println("List is empty");
        }
        else if (head.next == null)
        {
            head = null;
        }
        else
        {
            Node ptr = head;

            while (ptr.next.next != null)
            {
                ptr = ptr.next;
            }

            ptr.next = null;
        }
    }

    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);
        DeleteRear list = new DeleteRear();

        System.out.print("Number of nodes: ");
        int n = sc.nextInt();

        for (int i = 1; i <= n; i++)
        {
            System.out.print("Enter data: ");
            list.insertRear(sc.nextInt());
        }

        list.deleteRear();
        list.display();
    }
}
Input: Initial values: 10, 20, 30 Output: Linked list: 10 20
← Previous Program 54 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.