簡體   English   中英

使用遞歸打印反向鏈表

[英]Printing Reversed Linked List Using Recursion

我試圖以相反的順序打印一個鏈表,而不是使用遞歸來實際反轉它,但我的輸出非常奇怪。 看起來我的代碼基本上選擇第一個節點並在打印其余鏈表后打印它(按原始順序)。 我編寫的代碼(就我所見)是正確的,並且與 Internet 上針對此問題的代碼匹配。

這是我的代碼:

public class PrintLinkedListRecursively {

public static void printReverse(Node<Integer> temp) {
    if(temp == null) {
        return;
    }
    
    print(temp.next);
    System.out.print(temp.data);
    
}

public static Node<Integer> input() {
    Scanner scn = new Scanner(System.in);
    int data = scn.nextInt();
    Node<Integer> head = null, tail = null;
    
    while(data!=-1) {
        Node<Integer> currentNode = new Node<Integer>(data);
        if(head == null) {
            head = currentNode;
            tail = currentNode;
        }else {
            tail.next = currentNode;
            tail = tail.next;
        }
        
        data = scn.nextInt();
    }
    
    return head;
    
}

public static void main(String[] args) {        
    Node<Integer> head = input();
    printReverse(head);

}
}

這是節點類:

public class Node<T> {

T data;
Node<T> next;

Node(T data){
    this.data = data;
}
}

這是我給出的輸入,然后是輸出:

1 2 3 4 5 -1
2 3 4 5 1

這里發生的另一件奇怪的事情是,如果我改變了退出遞歸的條件,請說我是否這樣做:

if(temp.next.next.next == null){
   return;
}

然后是其余的原始代碼,它實際上仍然給我相同的輸出。 知道我哪里出錯了嗎?

嘗試將printReverse()函數重寫為:

public static void printReverse(Node<Integer> temp) {
    if(temp == null) {
        return;
    }
    printReverse(temp.next);
    System.out.print(temp.data);
}

暫無
暫無

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

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