Skip to main content

Print reverse view of linked list without modify in java

Java program for Print reverse view of linked list without modify. Here problem description and explanation.

// Java program for
// Print reverse of a linked list without actually reversing

// Linked list node
class LinkNode
{
    public int data;
    public LinkNode next;
    public LinkNode(int data)
    {
        this.data = data;
        this.next = null;
    }
}
public class SingleLL
{
    public LinkNode head;
    public LinkNode tail;
    public SingleLL()
    {
        this.head = null;
        this.tail = null;
    }
    // Add new Node at end of linked list 
    public void addNode(int data)
    {
        LinkNode node = new LinkNode(data);
        if (this.head == null)
        {
            this.head = node;
        }
        else
        {
            // Append the node at last position
            this.tail.next = node;
        }
        this.tail = node;
    }
    // Display reversal view of linked list using recursion
    public void printReverse(LinkNode node)
    {
        if (node == null)
        {
            return;
        }
        // Visit to next node
        this.printReverse(node.next);
        // Display node value
        System.out.print(" " + node.data);
    }
    public static void main(String[] args)
    {
        SingleLL sll = new SingleLL();
        //  1 → 2 → 8 → 4 → 9 → 6 → NULL
        sll.addNode(1);
        sll.addNode(2);
        sll.addNode(8);
        sll.addNode(4);
        sll.addNode(9);
        sll.addNode(6);
        // Reversal view
        // 6 9 4 8 2 1
        sll.printReverse(sll.head);
    }
}

Output

 6 9 4 8 2 1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment