簡體   English   中英

使用 toString 打印鏈表

[英]Printing out a linked list using toString

好的伙計們,所以我正在嘗試學習如何打印鏈表。 我擁有列表所需的所有方法,但我不知道如何顯示節點的值。 現在我的主要方法中沒有任何內容,因為我一直在嘗試調用主要方法中的非 static 方法時出錯。 我有一個顯示列表內容的 toString 方法。 我 go 如何調用此 toString 來顯示每個節點的值? 任何建議將不勝感激。

這是節點 class:

public class LinkedListNode
{

    private int data;
    private LinkedListNode next;


    public LinkedListNode(int data)
    {
        this.data = data;
        this.next = null;
    }

    public int getData()
    {
        return data;
    }

    public void setData(int d)
    {
        data = d;
    }

    public LinkedListNode getNext()
    {
        return next;
    }

    public void setNext(LinkedListNode n)
    {
        next = n;
    }
}

這是 LinkedList class,其中包含操作列表的主要方法和方法:

public class LinkedList {

    public LinkedListNode head;

    public static void main(String[] args) {

    LinkedList l = new LinkedList();
    l.insertFront(0);
    System.out.println(l.toString());

    }

    public LinkedList() {
        this.head = null;
    }

    public int removeFront(){
        if(head == null){
            System.out.println("Error - Attempting to call removeFront() on empty list");
            return 0;
        }else{
            int temp = head.getData();
            head = head.getNext();  
            return temp;
        }

    }

    public void insertFront(int data){
        if(head == null){
            head = new LinkedListNode(data);
        }else{
            LinkedListNode newNode = new LinkedListNode(data);
            newNode.setNext(head);
            head = newNode;
        }       
    }

    public void insertBack(int data){
        if(head == null){
            head = new LinkedListNode(data);
        }else{
            LinkedListNode newNode = new LinkedListNode(data);
            LinkedListNode current = head;
            while(current.getNext() != null){
                current = current.getNext();
            }
            current.setNext(newNode);
        }       
    }

    public int removeBack(){
        if(head == null){
            System.out.println("Error - Attempting to call removeBack() on empty list");
            return 0;
        }else if (head.getNext() == null){
            int temp = head.getData();
            head = null;
            return temp;
        }else{

            LinkedListNode current = head;
            while(current.getNext().getNext() != null){
                current = current.getNext();
            }
            int temp = current.getNext().getData();
            current.setNext(null);
            return temp;
        }       
    }

    public String toString(){
        String retStr = "Contents:\n";

        LinkedListNode current = head;
        while(current != null){
            retStr += current.getData() + "\n";
            current = current.getNext();

        }

        return retStr;
    }

    public LinkedListNode getHead() {
        return head;
    }

    public void setHead(LinkedListNode head) {
        this.head = head;
    }
}
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;
}

正如在其他一些答案和注釋中所指出的,這里缺少的是調用JVM System類來打印由toString()方法生成的字符串。

LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());

這將完成工作,但我不建議這樣做。 如果我們看一下Object類的javadocs,我們會找到toString()的這個描述:

返回對象的字符串表示形式。 通常,toString方法返回一個“文本表示”此對象的字符串。 結果應該是一個簡潔但信息豐富的表示 ,便於人們閱讀。 建議所有子類都重寫此方法。

這里強調的是我自己的。 您正在創建一個包含鏈表的整個狀態的字符串,有人使用您的類可能沒有預料到。 我建議進行以下更改:

  1. 將一個toString()方法添加到LinkedListNode類。
  2. 更新LinkedList類中的toString()方法更簡潔。
  3. 將一個名為printList()的新方法添加到您的LinkedList類中,該類執行您當前期望toString()執行的操作。

在LinkedListNode中:

public String toString(){
   return "LinkedListNode with data: " + getData();
}

在LinkedList中:

public int size(){
    int currentSize = 0;
    LinkedListNode current = head;
    while(current != null){
        currentSize = currentSize + 1;
        current = current.getNext();
    }

    return currentSize;
}

public String toString(){
    return "LinkedList with " + size() + "elements.";
}

public void printList(){
    System.out.println("Contents of " + toString());

    LinkedListNode current = head;
    while(current != null){
        System.out.println(current.toString());
        current = current.getNext();
    }

}

JVM嘗試運行您的應用程序時,它會靜態調用您的main方法; 這樣的事情:

LinkedList.main();

這意味着您沒有LinkedList類的實例。 為了調用toString()方法,您可以創建LinkedList類的新實例。

所以main方法的main應該是這樣的:

public static void main(String[] args){
    // creating an instance of LinkedList class
    LinkedList ll = new LinkedList();

    // adding some data to the list
    ll.insertFront(1);
    ll.insertFront(2);
    ll.insertFront(3);
    ll.insertBack(4);

    System.out.println(ll.toString());
}

我這樣做的方式如下:

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() {
    StringBuilder result = new StringBuilder();
    for(Object item:this) {
        result.append(item.toString());
        result.append("\n"); //optional
    }
    return result.toString();
}

一個非常簡單的解決方案是override NodetoString()方法。 然后,您可以通過傳遞LinkedListhead調用print。 您不需要實現任何類型的循環。

碼:

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

對於@Marin 代碼,如果列表為空或列表僅包含 1 個節點,則不涵蓋。 所以這里是改進的代碼:

 @Override
public String toString() {
    String result = "";
    LinkedListNode dummy = head;
    if (dummy == null) { //if list is empty return result
        return result;
    }else if(dummy.getNext() == null){ //if the list contains only 1 node
        result += dummy.getData();
        return result;
    }else{
        while(dummy != null){
            result += dummy.getData();
            if(dummy.getNext()!= null){
                result += " ";
            }
            dummy = dummy.getNext();
        }
        return result;
    }
    
    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM