【问题标题】:Implementing Linked List reversal using Stack使用 Stack 实现链表反转
【发布时间】:2016-03-20 05:30:53
【问题描述】:
我正在尝试使用 Stack 反转链接列表。
Node Reverse(Node head) {
Stack<Node> x = new Stack<Node>();
Node curr = new Node();
curr= head;
while (curr!=null){
x.push(curr);
curr=curr.next;
}
int i=0;
while(!x.isEmpty()){
if (i=0){
head=x.pop();
i++;
}
else{
Node temp = new Node();
temp = x.pop();
}
}
}
这是我的代码。我陷入了while循环。你能帮忙吗?
【问题讨论】:
标签:
data-structures
linked-list
stack
【解决方案1】:
您下面的代码将在一个while循环中无限运行。
if (i=0){
head=x.pop();
i++;
}
您应该将i=0 更改为i==0
if (i==0){
head=x.pop();
i++;
}
【解决方案2】:
Node Reverse(Node head) {
Stack<Node> x = new Stack<Node>();
Node curr = new Node();
curr= head;
while (curr!=null){
x.push(curr);
curr=curr.next;
}
Node temp = new Node();
temp=x.pop();
head=temp;
x.pop();
while(!x.isEmpty()){
temp = x.pop();
if (x.peek()!=null){
temp.next=x.peek();
}
else{
temp.next=null;
}
x.pop();
temp=temp.next;
}
return head;
}
我已经带头到这里了。但仍然无法处理空堆栈异常。
这不是最终解决方案。
【解决方案3】:
代码至少存在三个问题:
- 如前所述,
i=0 在if 语句的条件下应该是i==0;
- 当您从堆栈中弹出一个非头节点时,您没有进行任何链接;您可能应该说
prev.next = curr 之类的内容,其中curr 和prev 的定义很明显;
- 函数被定义为返回一个(引用)
Node;您提供的代码没有返回任何内容。
另外,我建议使用以下更简单、更高效的迭代方法。
/* ... */
typedef struct node_t_ node_t;
struct node_t_ {
node_t *next;
int v;
};
/* ... */
node_t *reverse(node_t *head) {
node_t *curr, *prev, *temp;
prev = NULL;
curr = head;
while (curr != NULL) {
temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
return prev;
}
我用 C 编写了代码;将其转换为 Java 应该没有问题。
【解决方案4】:
编程的核心是抽象。您可以通过抽象接口后面的链表来使您的代码更简单(因此也更容易)。完成后,通过堆栈进行反转就像这样简单:
void Reverse(LinkedList<T> list) {
Stack<T> stack = new Stack<T>();
while (! list.IsEmpty())
stack.Push(list.RemoveFront());
while (! stack.IsEmpty())
list.AppendBack(stack.Pop());
}
也就是说,将您的列表视为具有自己接口的单元,而不是在客户端代码中传递节点。节点只在LinkedList 类内部被触及。