【发布时间】:2010-11-10 03:28:00
【问题描述】:
我能想到的一种方法是反转列表然后阅读它。
但这涉及更改不好的列表。
或者我可以复制列表然后反转它,但这会使用额外的 O(n) 内存。
有没有更好的方法不使用额外的内存,不修改列表并在 O(n) 时间内运行
反向链表代码在c#中是这样的
Void Reverse (Node head)
{
Node prev= null;
Node current = head;
Node nextNode = null;
while (current!=null)
{
nextNode = current.Next;
current.Next = prev;
prev=current;
current = nextNode;
}
head = prev;
}
递归解是
void ReadBackWard (Node n)
{
if (n==null)
return;
else
ReadBackward(n.Next);
Console.WriteLine(n.Data);
}
【问题讨论】:
-
递归是你的朋友
-
@Neil:你能推荐一些使用递归的伪代码
-
但是递归使用 O(n) 内存
-
只有在使用 O(n) 额外内存的情况下,我们才能在 O(n) 时间内解决这个问题。请参阅下面的答案....谢谢大家的帮助....真的很棒,你们摇滚!!!....
-
尼尔:检查我的递归实现
标签: c# singly-linked-list