Printing out a linked list using toString

后端 未结 5 1594
耶瑟儿~
耶瑟儿~ 2020-12-06 13:19

Ok guys, so I am trying to learn how to print out a linked list. I have all the methods that I would need to use for the list, but I can\'t figure out how to display the va

5条回答
  •  悲哀的现实
    2020-12-06 14:06

    A very simple solution is to override the toString() method in the Node. Then, you can call print by passing LinkedList's head. You don't need to implement any kind of loop.

    Code:

    public class LinkedListNode {
        ...
    
        //New
        @Override
        public String toString() {
            return String.format("Node(%d, next = %s)", data, next);
        }
    } 
    
    
    public class LinkedList {
    
        public static void main(String[] args) {
    
            LinkedList l = new LinkedList();
            l.insertFront(0);
            l.insertFront(1);
            l.insertFront(2);
            l.insertFront(3);
    
            //New
            System.out.println(l.head);
        }
    }
    

提交回复
热议问题