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


my insert method explanation: assigned "next variable" of tail hold address of old node. assigned tail new node inserted list.

i tried display list starting tail , going through list until reached head.

problem: input displayed c not wanted. display method supposed display c, b, a.

i debug code on paper. don't know why display not retrieving last address of nodes linked in linked list. retrieved last node in list , display last node in 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);          // code executes first time when list has          // no node         if(head == null)         {             head = link;             tail= link;         }         // code execute when linked list has 1 or more node                                          else         {             tail.next = tail;             tail = link;          }     }      public void display()     {          while(tail != null)         {             system.out.println(tail.data);             tail = tail.next;          }      } 

you have created singly linked list. list has head , tail, links head tail. singly linked list design has 1 direction "forward". elements [a,b,c] list linked a->b->c. print elements in reverse order have @ least 2 options. use recursion print elements c , b, or implement doubly linked list


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -