📄 dbstack.cpp
字号:
#include"DbStack.h"
int InitStack(DbStack *Sp) //初始化一个空的双向栈
{
Sp->elem=(TYPE *)malloc(sizeof(TYPE)*STACK_SIZE);
if(!Sp->elem){
cout<<"存储分配失败!"<<endl; //存储分配失败
Sp->elem=NULL;
return FALSE;
}
Sp->top_1=0;
Sp->top_2=STACK_SIZE-1;
cout<<"双向栈已经初始化!"<<endl;
return TRUE;
}//InitStack
int DestroyStack(DbStack *Sp) //销毁一个双向栈
{
if(!Sp->elem){
cout<<"双向栈未初始化!"<<endl;
return FALSE;
}
free(Sp->elem);
Sp->elem=NULL;
cout<<"双向栈已经被销毁!"<<endl;
return TRUE;
}//DestroyStack
int GetLength(DbStack S,int n) //返回双向栈的长度
{
if(!S.elem){
cout<<"双向栈未初始化!"<<endl;
return FALSE;
}
if(n==1)
return S.top_1;
else
return STACK_SIZE-1-S.top_2;
}//GetLength
int StackDisplay(DbStack S,int n) //显示双向栈
{
int i,len,num;
if(!S.elem){
cout<<"双向栈未初始化!"<<endl;
return FALSE;
}
len=GetLength(S,n);
if(!len){
cout<<"The stack is empty!"<<endl;
return FALSE;
}
cout<<"栈"<<n<<"的所有元素为 :"<<endl;
if(n==1){
num=0;
for(i=0;i<len;i++){
cout<<S.elem[num++];
cout<<' ';
}
}
else{
num=STACK_SIZE-1;
for(i=0;i<len;i++){
cout<<S.elem[num--];
cout<<' ';
}
}
cout<<endl;
return TRUE;
}//StackDisplay
int Push(DbStack *Sp,int n,TYPE ele)//元素进栈
{
if(GetLength(*Sp,1)+GetLength(*Sp,2)==STACK_SIZE){
cout<<"双向栈已满,不能再进栈。"<<endl;
return FALSE;
}
if(n==1){
(Sp->elem)[Sp->top_1]=ele;
Sp->top_1++;
}
else{
(Sp->elem)[Sp->top_2]=ele;
Sp->top_2--;
}
return TRUE;
}//Push
int Pop(DbStack *Sp,int n,TYPE *elep)//元素出栈
{
if(n==1){
if(Sp->top_1==0){
cout<<"双向栈为空栈!"<<endl;
return FALSE;
}
*elep=Sp->elem[Sp->top_1--];
}
else{
if(Sp->top_2==STACK_SIZE-1){
cout<<"双向栈为空栈!"<<endl;
return FALSE;
}
*elep=Sp->elem[Sp->top_2++];
}
return TRUE;
}//Pop
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -