#include<iostream>
using namespace std;
const int stackinitsize=100;
const int stackincrement=10;
typedef struct
{
char *base;
char *top;
int stacksize;
} SqStack;
//輸出操作
void visit(char e)
{
cout<<(int)e<<endl;
}
//初始化
bool InitStack(SqStack &S)
{
S.base=(char *)malloc(stackinitsize*sizeof(char));
if(!S.base)
return false;
S.top=S.base;
S.stacksize=stackinitsize;
return true;
}
//銷燬
bool DestoryStack(SqStack &S)
{
while(S.base!=S.top)
{
free(S.top--);
}
free(S.top);
S.base=S.top=NULL;
S.stacksize=0;
return true;
}
//清除
bool ClearStack(SqStack &S)
{
S.top=S.base;
return true;
}
//判斷是否爲空
bool StackEmpty(SqStack S)
{
if(S.top==S.base)
return true;
else
return false;
}
//長度
int StackLength(SqStack S)
{
return S.stacksize;
}
//獲取棧頂元素
bool GetTop(SqStack S,char &e)
{
if(S.top==S.base)
return false;
e=*(S.top-1);
return true;
}
//壓棧
bool Push(SqStack &S,char e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(char *)realloc(S.base,(S.stacksize+stackincrement)*sizeof(char));
if(!S.base)
{
return false;
}
S.top=S.base+S.stacksize;
S.stacksize=S.stacksize+stackincrement;
}
*S.top++=e;
return true;
}
//退棧
bool Pop(SqStack &S,char &e)
{
if(S.top==S.base)
return false;
e=*(--S.top);
return true;
}
//從棧底向棧頂訪問
bool StackTraverse(SqStack S,void (*visit)(char e))
{
int i=0;
while((S.base+i)!=S.top)
{
visit(*(S.base+i));
i++;
}
return true;
}
int main()
{
SqStack S;
InitStack(S);
for(int i=0;i<10;i++)
Push(S,(char)i);
StackTraverse(S,visit);
for(int j=0;j<10;j++)
{
char e;
Pop(S,e);
printf("%d\n",e);
}
return 0;
}
棧(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.