作者:michael2502908531_893 | 来源:互联网 | 2023-10-11 21:53
#includeusingnamespacestd;constintMAXSIZE100;constintADD10;structstack{int*base;i
#include
using namespace std;
const int MAXSIZE = 100;
const int ADD = 10;
struct stack{
int * base;
int * top;
int size;
int ability;
};
void IntStack(stack & sta)//初始化
{
sta.base = (int *)malloc(MAXSIZE*sizeof(int));
sta.top = sta.base;
sta.ability = MAXSIZE;
sta.size = 0;
};
void push(stack & sta,int a)//出栈
{
if(sta.size >= sta.ability )
{
sta.base = (int*)realloc(sta.base,(sta.ability+ADD)*sizeof(int));
if(!sta.base) exit(0);
sta.top = sta.base + sta.size;
}
(*sta.top) = a;
sta.top++;
sta.size++;
}
int Pop(stack & sta)//入栈
{ if(sta.size>0)
{
sta.size--;
return *(--sta.top);
}
else
throw exception();
}
int GetSize(stack & sta)//返回栈长
{
return sta.size;
}
int GetTop(stack & sta)//返回栈顶元素
{
if(sta.size!=0)
{
return (*sta.base);
}
return -1;
}
void DestoryStack(stack & sta)//销毁
{
free(sta.base);
sta.base = sta.top;
}
void clear(stack & sta)//清空
{
//压缩存储空间
if(sta.ability>MAXSIZE)
{
free(sta.base);
sta.base = (int *)malloc(MAXSIZE*sizeof(int));
sta.ability = MAXSIZE;
}
sta.base = sta.top;
sta.size = 0;
}
bool StackTraverse(stack & sta,bool(* visit)(int &))//遍历调用
{
int * p = sta.base;
for(;p!=sta.top;p++)
{
if(!(visit(*p)))
{
return false;
}
}
return true;
}
bool fun(int & a)
{
a++;
return true;
}
int main()
{
stack myStack;//创建
IntStack(myStack);//初始化
cout<<"大小:"< push(myStack,1);//元素入栈
push(myStack,2);
push(myStack,3);
for(int *p = myStack.base;p!=myStack.top;p++)//遍历栈中的元素
cout<<(*p)<<" ";
cout< cout<<"大小:"< //所有元素出栈
for(;0!=myStack.size;)
{
cout< }
cout< push(myStack,4);//元素入栈
push(myStack,5);
push(myStack,6);
cout< StackTraverse(myStack,&fun);//处理栈中所有元素
for(int *p = myStack.base;p!=myStack.top;p++)//遍历栈中的元素
cout<<(*p)<<" ";
cout< cout<<"大小:"<}数据结构栈C++简单实现,布布扣,bubuko.com