linked list tutorial in java -



linked list tutorial in java -

i learning linked list in java , wrote sample code practise. singe linked list. code works fine reverses output. prints out cory, joe , tom , want output tom, joe , cory. tom beingness first node. how go or way single linked list works. reverses output?

public class linkedlist { public string name; public linkedlist next; public linkedlist(string name) { this.name = name; this.next = null; } public string tostring() { homecoming name; } public static void main(string[] args) { // todo auto-generated method stub linked l = new linked(); l.insert("tom"); l.insert("joe"); l.insert("cory"); l.print(); } } class linked { linkedlist first; public linked()//initialize { this.first = null; } public void insert(string name) { linkedlist g = new linkedlist(name); g.next = first; first = g; } //checks if list empty public boolean isempty() { homecoming (first ==null); } public void print() //displays list { linkedlist t = first; while(t!=null) { system.out.println(t); t = t.next; } } }

you inserting @ origin of linkedlist. if want add together insert new node after lastly node. need tail reference.

public string name; public linkedlist next; public linkedlist(string name) { this.name = name; this.next = null; } public string tostring() { homecoming name; } public static void main(string[] args) { // todo auto-generated method stub linked l = new linked(); l.insert("tom"); l.insert("joe"); l.insert("cory"); l.print(); } } class linked { linkedlist first; linkedlist tail; public linked()//initialize { this.first = null; this.tail = first; } public void insert(string name) { linkedlist g = new test(name); if(isempty()) { first = g; tail = first; } else { tail.next = g; tail = g; } } //checks if list empty public boolean isempty() { homecoming (first ==null); } public void print() //displays list { linkedlist t = first; while(t!=null) { system.out.println(t); t = t.next; } }

if notice added tail reference , instead of inserting new object @ origin attach end of linkedlist. alter method name add. in fact have 2 methods maintain yours how is...then add together new method insert phone call add together way insert @ origin or add together end of linkedlist.

java linked-list

Comments

Popular posts from this blog

c - Compilation of a code: unkown type name string -

java - Bypassing "final local variable defined in an enclosing type" -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -