簡體   English   中英

在鏈表中反向打印

[英]Print reverse in linkedlist

我想用Java編寫LinkedList的反向打印功能。 我這樣寫,但是行不通。 編譯器警告NullPointerException

void ReversePrint(Node head) {
    int[] array = null;
    int i = 0;
    Node tmp;
    for (tmp = head; tmp != null; tmp = tmp.next) {
        array[i] = tmp.data;
        i++;
    }
    for(int j = i; j >= 0; j--){
        System.out.println(array[j]);
    }
}

您會收到NullPointerException因為變量arraynull

int[] array = null;

您需要先使用一個值對其進行初始化,然后才能在此處使用它:

array[i] = tmp.data;

例如,帶有如下語句:

int[] array = new int[size];

size可能應該是LinkedList的大小。 如果您出於某種原因不知道大小,則可以使用ArrayList類,該類實現具有動態大小的數組(它會猜測一個大小,如果超過該大小,它將重新分配一個更大的數組,然后將所有內容復制並依此類推)。

這是使用ArrayList的版本:

// Method names should start with a lower-case letter
void reversePrint(Node head) {
    // Initialize an empty ArrayList
    ArrayList<Integer> dataList = new ArrayList<>();
    int i = 0;
    Node tmp;
    for (tmp = head; tmp != null; tmp = tmp.next) {
        // Set the element at position i of the ArrayList
        dataList.set(i, tmp.data);
        i++;
    }

    // See next comment
    i--;

    for(int j = i; j >= 0; j--){
        // Get the element at position j of ArrayList and print it
        System.out.println(dataList.get(j));
    }
}

請注意,由於到達打印循環時i11 ,因此您還將遇到IndexOutOfBoundException 這是因為您也在第一個循環的最后一次迭代中增加了它:

// Suppose last iteration, i is (list.size() - 1) then
for (tmp = head; tmp != null; tmp = tmp.next) {
    array[i] = tmp.data;
    // i is now list.size()
    i++;
}

在循環初始化中,您需要在循環之間添加一個i--int j = i - 1


如果要實現一個雙向鏈接列表而不是一個單鏈接列表,請注意,您不需要首先對數組中的值進行故事化。 然后,您可以通過從tail開始並跟隨tmp.prev指針直接打印值。

最簡單的方法是使用遞歸方法:

void ReversePrint(Node node) {
    if (node != null) {
        ReversePrint(node.next);
        System.out.println(node.data);
    }
}

暫無
暫無

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

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