gpt4 book ai didi

java - 在java中反转并打印单链表

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:31 25 4
gpt4 key购买 nike

我编写了这个程序,可以反转单链表并打印它。问题是我无法打印相反的顺序,它给了我 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;

}
}

最佳答案

更改您的代码如下:

 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

关于java - 在java中反转并打印单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26716468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com