printing nodes from a singly-linked list

可紊 提交于 2019-12-23 03:49:14

问题


I made a node class which is a linked list class. Is there any way I can print out elements in this list ? I made my print() method but it only returns the first element which is 21. How do I iterate through that list ?

public class ListNode {
    private int item;
    private ListNode next;

    public ListNode(int item, ListNode next){
        this.item = item;
        this.next = next;
    }

    public ListNode(int item){
        this(item, null);
    }

    public int print(){
        return item;
    }

    public static void main(String[] args) {            
        ListNode list = new ListNode(21, new ListNode(5, new ListNode(19, null)));
        System.out.println(list.print());
    }

}


回答1:


public String toString() {
    String result = item + " ";
    if (next != null) {
        result += next.toString();
    }
    return result;
}

And then you can simply do

System.out.println(list.toString());

(I renamed your function from print to toString to give a more accurate description of what it does)




回答2:


Your current implementation doesn't print anything: it simply returns item. More appropriate implementation would look like:

public void print() {
    System.out.println(item); 
}

You can then use recursion to print all items:

public void printAll() {
    print();
    if (next != null) {
        System.out.println("; ");
        next.printAll(); 
    }
}



回答3:


Consider creating a printall

public void printAll(){
    System.out.println(item);
    if (next != null){
        next.printAll();
    }
}



回答4:


Your print() function is returning only a single item that's why it is printing only 21.

Call recursively to print all the values until next != NULL




回答5:


Calling list.print() will only ever return the value of the head (21) - you are never making any reference or call to the next node: next.

Personally, I would remove the print() method and instead override toString():

@override
public String toString(){
    return item + "\n" + next;
}

I guess you probably don't want the null tail printed, so this is probably nicer:

@override
public String toString(){
    if(next) {
        return item + "\n" + next;
    } else {
        return item + "\n";
    }
}

Then in, main:

public static void main(String[] args) {            
    ListNode list = new ListNode(21, new ListNode(5, new ListNode(19, null)));
    System.out.println(list);
}



回答6:


You can use a foreach loop:

List<ListNode> theList = new LinkedList<ListNode>();
//add stuff to the list
for(ListNode n:theList)
   System.out.println(n.print();

THis will iterate over the list and return the next object, on this object we call the print() method



来源:https://stackoverflow.com/questions/16565045/printing-nodes-from-a-singly-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!