zoukankan      html  css  js  c++  java
  • 实现顺序栈的各种基本运算

    实现顺序栈的各种基本运算

    功能描述

    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;
     } 
    
    欢迎评论交流!
  • 相关阅读:
    [GL]行星运行1
    一个图的带权邻接表存储结构的应用
    [GDAL]3.影像金字塔构建
    [GDAL]1.GDAL1.8.1编译与第一个程序
    [GDAL]2.读取栅格和矢量数据
    C#迭代器
    GoogleEarth缓存机制探索
    AE开发三维的不足!
    [GDAL]4.影像的读取和显示
    [STL学习]1.概述
  • 原文地址:https://www.cnblogs.com/alking1001/p/11887143.html
Copyright © 2011-2022 走看看