在java中反转和打印单链表

时间:2014-11-03 14:41:05

标签: java linked-list singly-linked-list

我编写了这个程序,可以反转单个链表并打印出来。问题是我无法打印相反的顺序,它给了我StackOverFlowError。问题可能在于我的反向方法。任何帮助将不胜感激。

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;

}
}

1 个答案:

答案 0 :(得分:0)

更改您的代码如下:

 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