簡體   English   中英

在Java中反轉並打印單鏈列表

[英]Reversing and printing a singly linked list in java

我已經編寫了該程序,該程序可以反轉單鏈列表並打印出來。 問題是我無法打印相反的順序,這給了我StackOverFlowError。 問題可能出在我的Reverse方法上。 任何幫助將不勝感激。

private static Node head;

public static void main(String[] args) 
{
    GettingNumbers();
}

public static void Reverse(Node node)
{
    if (node != null)
    {
        Reverse(node.next);
        System.out.print(" " + node.key);
    }
}
public static void GettingNumbers()
{   
    head = new Node();
    head = null;
    Node last = new Node();
    String str = new String();

    System.out.print("Enter a number or # to stop: ");
    str = console.next();

    while (!(str.trim().equals("#")))
    {
        Node node = new Node();
        node.key = str;
        node.next= null;

        if (head == null)
        {
            head = node;
            last = node;
        }
        else
        {
            last.next = node;
            last = node;
        }

        System.out.print("Enter a number or # to stop: ");
        str = console.next();
    }
    Node h = head;
    if (head == null || head.next == null)
    {
        return;  //empty or just one node in list
    }

    Node Second = head.next;

    //store third node before we change 
    Node Third = Second.next;  

    //Second's next pointer
    Second.next = head;  //second now points to head
    head.next = null;  //change head pointer to NULL

    //only two nodes, which we already reversed
    if (Third == null)
    {
        return;  
    }

    Node CurrentNode = Third;

    Node PreviousNode = Second;

    while (CurrentNode != null)
    { 
        Node NextNode = CurrentNode.next;

        CurrentNode.next = PreviousNode;

        /*  repeat the process, but have to reset
             the PreviousNode and CurrentNode
        */

        PreviousNode = CurrentNode;
        CurrentNode = NextNode;  

    }

    head  = PreviousNode; //reset the head node
    Reverse(h);

    return;

}
}

如下更改代碼:

 Node previousNode=null;
      Node nextNode;
      while(currentNode!=null)
      {
       nextNode=currentNode.next;
      // reversing the link
       currentNode.next=previousNode;
      // moving currentNode and previousNode by 1 node
       previousNode=currentNode;
       currentNode=nextNode;
      }

看看這個答案並進行詳細說明: https : //stackoverflow.com/a/44068199/3148734

暫無
暫無

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

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