Nicholas
Nicholas

Reputation: 679

Unable to display nodes of the list properly starting from the tail to head

My insert method explanation: I assigned the "next variable" of tail to hold the address of the old node. I assigned the tail with the new node inserted into the list.

I tried to display the list starting from the tail and going through the list until it reached the head.

Problem: But the input displayed C which is not what I wanted. Display method is supposed to display C, B, A.

I even debug my code on paper. I don't know why the display is not retrieving the last address of the nodes linked in the linked list. It only retrieved the last node in the list and display only that last node in the list.

public static void main(String[] args)
    {
        LinkedList list = new LinkedList();
        list.insert("A");
        list.insert("B");
        list.insert("C");
        list.display();

    }

public void insert(String data)
    {
        Link link = new Link(data);

        // this code only executes the first time when the list has 
        // no node
        if(head == null)
        {
            head = link;
            tail= link;
        }
        // this code will execute when the linked list has one or more node                                 
        else
        {
            tail.next = tail;
            tail = link;

        }
    }

    public void display()
    {

        while(tail != null)
        {
            System.out.println(tail.data);
            tail = tail.next;

        }

    }

Upvotes: 1

Views: 184

Answers (1)

Paxic
Paxic

Reputation: 1760

You have created a singly linked list. The list has a head and tail, the links are from head to tail. A singly linked list by design has one direction "forward". With elements [a,b,c] the list is linked a->b->c. To print the elements in reverse order you have at least two options. Use recursion to print the elements c , b, a or implement a doubly linked list

Upvotes: 1

Related Questions