Wednesday 15 September 2010

class - Java - Traversing a linked list only returns null -



class - Java - Traversing a linked list only returns null -

i'm studying linked lists. help book cracking coding interview, created next code create linked lists, add together elements end , print elements. when run code, returns "null" instead of printing list i.e. "sanchez". "ozil" , "welbeck". help?

public class createlinkedlist{ static class node{ string playername; node next = null; //constructor node(string pname){ playername = pname; } //method insert node void insertnodeatend(string playername){ node transition = new node(playername); node n = this; while(n.next != null){ n = n.next; } n.next = transition; } //method print elements of linked list void printlist(){ node n = this; while (n.next != null){ system.out.println(n.playername + "\n"); n = n.next; } } } public static void main(string[] args) { node first = new node("sanchez"); first.insertnodeatend("ozil"); first.insertnodeatend("welbeck"); first.printlist(); } }

public class createlinkedlist { static class node { string playername; node next = null; // constructor node(string pname) { playername = pname; } // method insert node void insertnodeatend(string playername) { node transition = new node(playername); node n = this; while (n.next != null) { n = n.next; } n.next = transition; } // method print elements of linked list void printlist() { node n = this; while (n != null) { system.out.println(n.playername + "\n"); n = n.next; } } } public static void main(string[] args) { node first = new node("sanchez"); first.insertnodeatend("ozil"); first.insertnodeatend("welbeck"); first.printlist(); } }

output

sanchez ozil welbeck

java class methods linked-list system.out

No comments:

Post a Comment