实现顺序栈的各种基本运算
功能描述
struct Sqstack //栈的结构
{
int *base;
int *top;
int size;
};
bool init(Sqstack &S); //初始化函数
bool isempty(Sqstack &S);
bool push(Sqstack &S, int e); //第二个元素是要进栈的元素
bool pop(Sqstack &S, int &e); //第二个参数是要出栈的元素
bool clear(Sqstack &S); //清空栈
void initRandomize(int *arr, int n, int min, int max);//随机数生成函数
代码实现
#include<bits/stdc++.h>
using namespace std;
const int stack_size=100;
const int increment=100;
struct Sqstack
{
int *base;
int *top;
int size;
};
bool init(Sqstack &S)
{
S.base=(int*) malloc(stack_size*sizeof(int));
if(S.base==NULL)
return false;
S.top=S.base;
S.size=stack_size;
return true;
}
bool isempty(Sqstack &S)
{
if(S.base==S.top)
return true;
else return false;
}
bool push(Sqstack &S, int e) //第二个元素是要进栈的元素
{
if(S.top-S.base >= S.size)
{
S.base=(int *) realloc(S.base, (S.size+increment)*sizeof(int));
if(S.base==NULL)
return false;
S.top=S.base+S.size;
S.size+=increment;
}
*S.top=e;
S.top++;
return true;
}
bool pop(Sqstack &S, int &e) //第二个参数是要出栈的元素
{
if(S.top<=S.base)
return false;
S.top--;
e=*S.top;
return true;
}
bool clear(Sqstack &S)
{
if(S.base!=NULL)
free(S.base);
S.base=NULL;
S.top=NULL;
return true;
}
/*
产生n个[min, max]的随机数。可能会有重复值。
*/
void initRandomize(int *arr, int n, int min, int max)
{
int i = 0;
srand(time(0)); /*设置种子,并生成伪随机序列*/
for (i = 0; i < n; ++i) {
arr[i] = rand() % (max - min + 1) + min; /*得到从[min, max]之间的随机数*/
printf("%d ", arr[i]);
}
printf("
");
}
int main()
{
int num[100];
Sqstack S;
if(init(S))
cout<<"栈初始化成功
";
else
cout<<"栈初始化失败
";
cout<<"随机数如下:
";
initRandomize(num, 10, 0, 100);
for(int i=0; i<10; i++)
{
if( !push(S, num[i]) )
{
cout<<"push出现问题,push操作停止
";
break;
}
}
int e;
cout<<"下面将栈里面的内容全部出栈
";
while(!isempty(S))
{
if(!pop(S, e))
{
cout<<"pop出现问题,pop操作停止
";
break;
}
cout<<e<<" ";
}
cout<<endl<<endl;
if(clear(S))
cout<<"释放栈成功
";
else
cout<<"释放栈失败
";
return 0;
}