#include <iostream> / File: int-stack.h /
#include <cstdlib>
using namespace std;
const int BUFFER SIZE = 100;
class int stack
{
private:
int data[BUFFER SIZE]; // Use an array to store data
int top_index; // Start from 0; -1 when empty
public:
int stack(void); // Default constructor
bool empty(void) const; // Check if the stack is empty
bool full(void) const; // Check if the stack is full
int size(void) const; // Give the number of items currently stored
int top(void) const; // Retrieve the value of the top item
void push(int); // Add a new item to the top of the stack
void pop(void); // Remove the top item from the stack
void insert_at_bottom(int_stack& stack, int item); //adds a new item to the bottom of the stack if the stack is not full.
};
鉴于这些函数,我需要实现一个名为 reverse_stack(int_stack& stack) 的函数。这是使用递归的建议解决方案,
void reverse_stack(int_stack& stack)
{
if (stack.empty())
return;
else
{
int top_item = stack.top();
stack.pop();
reverse_stack(stack);
insert_at_bottom(stack, top_item);
}
}
我的解决方案是这样的,我想知道它是否正确。
void reverse_stack(int_stack& stack){
while(stack.empty() == false){
insert_at_bottom(stack,stack.top());
stack.pop();
}
不,它不是。
你的功能:
void reverse_stack(int_stack& stack){
while(stack.empty() == false){
insert_at_bottom(stack,stack.top());
stack.pop();
}
在弹出堆栈之后,您在循环中缺少一个右括号。
我的解决方案是这样的,我想知道它是否正确。
您应该编写一些代码来测试该功能。如果你发现它不起作用,你应该得到一张纸并画出你的代码的作用,这样你就会看到哪里出了问题。
您的函数执行此操作(对于非空堆栈):
---
|1|
---
|2|
---
|3|
---
在底部插入顶部元素:
---
|1|
---
|2|
---
|3|
---
|1|
---
弹出顶部元素:
---
|2|
---
|3|
---
|1|
---
在底部插入顶部元素:
---
|2|
---
|3|
---
|1|
---
|2|
---
弹出顶部元素:
---
|3|
---
|1|
---
|2|
---
在底部插入顶部元素:
---
|3|
---
|1|
---
|2|
---
|3|
---
弹出工具元素:
---
|1|
---
|2|
---
|3|
---
就在这个时候,你的函数肯定知道错了!您的堆栈与调用该函数之前完全相同!
顺便问一下,你的函数什么时候终止?正如现在写的那样,它将运行一个无限循环!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句