zoukankan      html  css  js  c++  java
  • 栈的基本操作 出栈与入栈

    #include<stdio.h>
    #include<stdlib.h>
    #define LENGTH 100	//初始分配栈的长度
    #define ADD_LEN 10	//栈长增量
    typedef struct 
    {//构造栈的数据类型 
    	int *base;
    	int *top;
    	int stacksize;
    }SqStack;
    void CreateStack(SqStack &S);//初始化一个栈
    void PushStack(SqStack &S,int e);//e进栈
    void PopStack(SqStack &S);//栈顶元素出栈
    void DestroyStack(SqStack &S);//销毁栈
    void PrintfStack(SqStack &S);//输出当前的栈
    void main()
    {	SqStack Sa;
    	int m,n;
    	CreateStack(Sa);
    	printf("Please input the total of inserting number:");
    	scanf("%d",&m);
    	while(m>LENGTH)
    	{	printf("The number you input can't be larger than %d,please input again:
    ",LENGTH);
    		scanf("%d",&m);
    	}
    	while(m--)
    	{	printf("Please input a number to insert:");
    		scanf("%d",&n);
    		PushStack(Sa,n);
    	}
    	PrintfStack(Sa);
    	PopStack(Sa);
    	PrintfStack(Sa);
    	DestroyStack(Sa);
    }
    void CreateStack(SqStack &S)
    {	S.base=(int *)malloc(LENGTH*sizeof(int));
    	if(!S.base)
    	{	printf("Fail to create stack!
    ");
    		return;
    	}
    	S.top=S.base;
    	S.stacksize=LENGTH;
    	printf("Success to create stack!
    ");
    }
    void PushStack(SqStack &S,int e)
    {	if(S.top-S.base>=S.stacksize)//考虑栈是否已满,如满。则从新分配空间
    	{	S.base=(int *)realloc(S.base,(S.stacksize+ADD_LEN)*sizeof(int));
    		if(!S.base)
    			return;
    		S.top=S.base+S.stacksize;
    		S.stacksize+=ADD_LEN;
    	}
    	*S.top++=e;
    	printf("%d success to insert the stack!
    ",e);
    } 
    void PopStack(SqStack &S)
    {	int m;
    	if(S.top==S.base)
    	{	printf("The stack is empty!
    ");
    		return;
    	}
    	m=*--S.top;
    	printf("%d is out of the stack!
    ",m);
    }
    void DestroyStack(SqStack &S)
    {	free(S.base);//释放空间
    	S.base=NULL;
    	*S.top=-1;//将其它成员设置成安全值
    	S.stacksize=0;
    	printf("Success to destroy the stack!
    ");
    }
    void PrintfStack(SqStack &S)
    {	int *p;
    	p=S.top;
    	printf("The stack is :");
    	while(--p>=S.base)
    		printf("%d",*p);
    	printf("
    ");
    }

  • 相关阅读:
    python之字典
    Python包管理工具
    【转】Python实现修改Windows CMD命令行输出颜色(完全解析)
    进程池中传递实例方法问题
    HTML协议详解
    【转】python数据格式化之pprint
    【转】Python装饰器与面向切面编程
    【转】TCP/IP报文格式
    python之线程学习
    python之面向对象
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7168253.html
Copyright © 2011-2022 走看看