这个程序应该使用一个后缀算术表达式,然后编译该表达式的值。每次读取一个整数,它将被推入堆栈。否则,如果+, - ,*是,则会弹出两个整数读取。
class Stack {
Node *head;
public:
Stack() {
head = NULL;
};
void push(int data);
int pop();
bool isEmpty();
void print();
};
void Stack::push(int data)
{
Node * temp = new Node(data);
temp->next = head;
head = temp;
delete temp;
}
int Stack::pop()
{
int x = head->data;
head = head->next;
return x;
}
bool Stack::isEmpty(){
return head == NULL;
}
void Stack::print(){
Node * temp = head;
while (temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
delete temp;
}
int main() {
Stack st;
char exp [] = "23+", c;
int i, a;
for (i = 0; exp[i] != '\0'; i++){
c = exp[i];
if (c == '+'&&!st.isEmpty()){
a = st.pop() + st.pop();
st.push(a);
}
else if (c == '-'&&!st.isEmpty()){
a = st.pop() - st.pop();
st.push(a);
}
else if (c == '/'&&!st.isEmpty()){
a = st.pop() / st.pop();
st.push(a);
}
else if (c == '*'&&!st.isEmpty()){
a = st.pop() * st.pop();
st.push(a);
}
else if (c == '0')
st.push(0);
else if (c == '1')
st.push(1);
else if (c == '2')
st.push(2);
else if (c == '3')
st.push(3);
else if (c == '4')
st.push(4);
else if (c == '5')
st.push(5);
else if (c == '6')
st.push(6);
else if (c == '7')
st.push(7);
else if (c == '8')
st.push(8);
else if (c == '9')
st.push(9);
cout << c << endl;
st.print();
}
cin >> a;
return 0;
}
当我在main中调用print函数时,我得到一个无限循环作为输出。 我试着寻找导致无限循环的东西,但我找不到它。
答案 0 :(得分:3)
我看到的问题:
在delete
中使用push()
:
void Stack::push(int data)
{
Node * temp = new Node(data);
temp->next = head;
head = temp;
delete temp; // This needs to go.
}
未在delete
中使用pop()
:
int Stack::pop()
{
// Problem 1.
// What if head is NULL?
int x = head->data;
// Problem 2
// The old value of head is gone. It's a memory leak.
head = head->next;
return x;
}
你需要:
int Stack::pop()
{
if ( head != NULL )
{
int x = head->data;
Node * temp = head;
head = head->next;
delete temp;
return x;
}
else
{
// Figure out what you want to do if head is NULL
}
}
在delete
中使用print()
。
void Stack::print(){
Node * temp = head;
while (temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
delete temp; // This needs to go.
}
缺少用户定义的析构函数。您需要删除对象中的对象。否则,你正在泄漏记忆。以下代码中的某些内容应该有效。
Stack::~Stack()
{
while (head)
{
Node * temp = head;
head = head->next;
delete temp;
}
}
答案 1 :(得分:1)
以下是push
和pop
的建议。
尝试理解逻辑。
void Stack::push(int data)
{
Node * temp = new Node(data);
temp->next=head;
head=temp;
//Do not delete temp; deleting temp will delete the new added Node
}
int Stack::pop()
{
Node* temp = Head;
int x=head->data;
head=head->next;
delete temp; //here you free the released memory.
return x;
}
此外,对于代码中的每个数字,所有if / else都可以执行以下操作:
else if(c>=0 && c<=9){
st.push(c-'0');
}