Printing out a linked list using toString

后端 未结 5 1596
耶瑟儿~
耶瑟儿~ 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:10

    public static void main(String[] args) {
    
        LinkedList list = new LinkedList();
        list.insertFront(1);
        list.insertFront(2);
        list.insertFront(3);
        System.out.println(list.toString());
    }
    
    String toString() {
                String result = "";
                LinkedListNode current = head;
                while(current.getNext() != null){
                    result += current.getData();
                    if(current.getNext() != null){
                         result += ", ";
                    }
                    current = current.getNext();
                }
                return "List: " + result;
    }
    

提交回复
热议问题