在我的实现中使用堆栈是否正确?

时间:2017-05-20 08:28:12

标签: c++ function loops data-structures stack

U.fromList [U.fromList [1..5], U.fromList [1..7]]

鉴于这些功能,我需要实现一个名为reverse_stack(int_stack& stack)的函数。 这是使用递归的建议解决方案,

#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.
};

我的解决方案就是这个,我想知道它是否正确。

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); 
}
}

1 个答案:

答案 0 :(得分:2)

,不是。

你的职能:

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|
---

Pop tol元素:

---
|1|
---
|2|
---
|3|
---

就在这时,你的功能肯定知道这是错的!您的堆栈与调用函数之前完全相同!

顺便问一下,你的功能什么时候会终止?正如现在所写,它将运行无限循环