【发布时间】:2014-12-30 05:46:35
【问题描述】:
我编写了这个程序,它反转一个单链表并打印它。问题是我无法打印相反的顺序,它给了我 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;
}
}
【问题讨论】:
-
递归遍历列表的问题在于,您最终会在内存堆栈上为列表中的每个元素调用一个方法。一旦列表超出了微不足道的大小,您就有可能使用所有内存并获得
StackOverflowError -
您应该删除所有
SecondNode、ThirdNode内容以尝试本地化问题。你有这么多奇怪的东西,很难确定你是否在列表中创建了一个外观。 -
这两行所说的
head = new Node(); head = null; -
评论更新...很难确定您是否在列表中创建了循环。这通常是导致此错误的原因:循环或递归太深。
标签: java linked-list singly-linked-list