我正在通过编写基于指针的动态堆栈在c++中创建一个反向波兰表示法整数计算器,但是我在MyStack类中使用toString方法遇到了麻烦。
这是我的代码应该如何工作的一些背景:
方法说明:
constructor
:初始化对象,设置必要的内存。 destructor
:释放对象可能需要释放的所有内存。 clear()
:清空堆栈。 pop()
:删除并返回栈顶值(如果不为空)。如果尝试弹出时堆栈为空,则引发异常。选择任何异常(exception)。 push(int)
:接受整数作为唯一参数,如果有足够的内存,则将其压入堆栈。 size()
:以整数形式返回堆栈的大小。 toString()
:返回堆栈的字符串表示形式。例如,如果堆栈中包含顶部的8, 3, 2, 5
的8
,则它将返回[8, 3, 2, 5]
,其格式完全相同。 计算器将需要支持以下操作:
+
:附加-
:减法*
:乘法/
:分区%
:模量?
:使用toString()方法将堆栈的当前内容打印到屏幕上。 ^
:弹出堆栈顶部,仅显示弹出的值。 !
:退出计算器。 计算器将连续读取输入,直到!输入。它可以读取任意数量的 token 作为输入(请参见下文)。如果堆栈中没有足够的整数来执行计算,则应显示
#Not enough arguments.
。如果输入了除整数以外的任何内容或受支持的操作,则应显示错误消息#Invalid input.
,而不会中断特定输入行的其余操作。我在使用toString方法时遇到麻烦。如何将整数堆栈转换为字符串?
我的代码:
// main.cpp
// practice2
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
#include <stack>
using namespace std;
struct Node
{
int data;
Node *next;
};
class MyStack
{
private:
Node *top;
public:
MyStack();
~MyStack();
void clear();
void push(int);
int pop();
int size();
string toString();
bool isEmpty();
};
MyStack::MyStack()
{
top = NULL;
};
MyStack::~MyStack()
{
while(!isEmpty())
{
pop();
}
};
void MyStack::push(int d)
{
Node *temp = new Node;
temp->data = d;
temp->next = top;
top = temp;
}
int MyStack::pop()
{
if(!isEmpty())
{
int value = top->data;
Node *oldtop = top;
top = oldtop->next;
delete oldtop;
return value;
} else
{
cout << "stack is empty"; //throw exception
exit(1);
}
}
string MyStack::toString()
{
//redo later
};
bool MyStack::isEmpty()
{
return (top == NULL);
}
int main()
{
MyStack *s = new MyStack();
s->push(8);
s->push(3);
s->push(2);
s->push(5);
delete s;
return 0;
}
预期产量:
toString()
:返回堆栈的字符串表示形式。例如,如果堆栈中包含顶部的8, 3, 2, 5
的8
,则它将返回[8, 3, 2, 5]
,其格式完全相同。 最佳答案
就像是
string MyStack::toString()
{
string result = "[";
bool needs_comma = false;
for (Node* temp = top; temp != nullptr; temp = temp->next) {
if (needs_comma) result += ", ";
needs_comma = true;
result += std::to_string(temp->data);
}
result += "]";
return result;
};
应该可以。