Search code examples
javasingly-linked-list

printing nodes from a singly-linked list


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());
    }

}


Solution

  • 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)