#include
using namespace std;
#define maxsize 100
struct mystack
{
int * top;
int * base;
int size;
};
struct mystack*createstack()
{
struct mystack* newstack = new mystack[100];
newstack->top = newstack->base;
newstack->size = maxsize;
return newstack;
}
bool empty(struct mystack*newstack)
{
if (newstack->base = newstack->top)
{
cout << "该栈为空" << endl;
return 1;
}
else
return 0;
}
bool full(struct mystack* newstack)
{
if (newstack->top - newstack->base == newstack->size)
{
cout << "该栈为满" << endl;
return 1;
}
else
return 0;
}
void push(struct mystack* newstack,int e)
{
if(full(newstack))
{
return;
}
*(newstack->top)= e;
newstack->top++;
}
int pop(struct mystack* newstack)
{
int e;
if (empty(newstack))
{
return 0;
}
newstack->top--;
e = *(newstack->top);
return e;
}
int main()
{
struct mystack* newstack = createstack();
push(newstack, 1);
push(newstack, 2);
push(newstack, 3);
while (!empty(newstack))
{
cout<newstack)<<' ';
}
}
nide代码存在以下几个问题:
1.结构体指针newstack只申请了一个元素的空间,而不是100个元素的空间。应该将“struct mystack* newstack = new mystack[100];”改为“struct mystack* newstack = new mystack();”。
2.在empty函数中,进行if判断时,应该用==而不是=,因为=是赋值符号,会改变变量的值。
3.在empty和full函数中,如果栈为空或者为满,函数应该直接返回true,而不是返回1。
4.在pop函数中,如果栈为空,应该输出提示信息并且直接返回0,而不是返回e。
修改后的代码:
#include<iostream>
using namespace std;
#define maxsize 100
struct mystack
{
int * top;
int * base;
int size;
};
struct mystack* createstack()
{
struct mystack* newstack = new mystack();
newstack->top = newstack->base;
newstack->size = maxsize;
return newstack;
}
bool empty(struct mystack* newstack)
{
if (newstack->base == newstack->top)
{
cout << "该栈为空" << endl;
return true;
}
else
return false;
}
bool full(struct mystack* newstack)
{
if (newstack->top - newstack->base == newstack->size)
{
cout << "该栈为满" << endl;
return true;
}
else
return false;
}
void push(struct mystack* newstack, int e)
{
if (full(newstack))
{
return;
}
*(newstack->top) = e;
newstack->top++;
}
int pop(struct mystack* newstack)
{
if (empty(newstack))
{
cout << "该栈为空" << endl;
return 0;
}
newstack->top--;
int e = *(newstack->top);
return e;
}
int main()
{
struct mystack* newstack = createstack();
push(newstack, 1);
push(newstack, 2);
push(newstack, 3);
while (!empty(newstack))
{
cout << pop(newstack) << ' ';
}
cout << endl;
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:算法思想:
1)初始设置一个空栈,顺序读入括号。
2)若是右括号,则或者使置于栈顶的最急迫期待得以消解,或者是不合法的情况(括号序列不匹配,则退出程序。
3)若是左括号,则作为一个新的更急迫的期待压入栈中,使原有的在栈中的所有未消解的期待的急迫性降了一级。算法结束时,栈为空,否则括号序列不匹配。