📄 栈.cpp
字号:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct{
int *base;
int *top;
int stacksize;
}Sqstack;
//创建一个空栈
void Inistack(Sqstack &s)
{
s.base=(int*)malloc(STACK_INIT_SIZE * sizeof(int) );
if(!s.base)
{
printf("创建空栈失败!\n");
exit(0);
}
s.top=s.base;
s.stacksize=STACK_INIT_SIZE;
printf("成功创建一个空栈。\n");
}
//毁掉一个栈
void Destroystack(Sqstack s)
{
s.base=NULL;
printf("栈已经被销毁!\n");
}
//清空一个栈
void Clearstack(Sqstack &s)
{
s.base=s.top;
printf("栈已经被清空!\n");
}
//创建一个栈
void Createstack(Sqstack &s)
{
int a,n=0;
s.base=(int*)malloc(STACK_INIT_SIZE * sizeof(int) );
s.top=s.base;
if(!s.base)
{
printf("申请空间失败!\n");
exit(0);
}
printf("input a number (if(0)stop)\n");
scanf("%d",&a);
while(a!=0)
{
*s.top++=a;
printf("input a number (if(0)stop)\n");
scanf("%d",&a);
}
}
//将栈里的元素输出
void printstack(Sqstack s)
{
int d;
while(s.top!=s.base)
{
d=*s.base++;
printf("%d\t",d);
}
}
//输出栈顶元素
void Gettop(Sqstack s, int &e)
{
if(s.top==s.base)
printf("栈是空的!\n");
e=*(s.top-1);
}
//插入新的元素作为栈顶元素
void Push(Sqstack &s,int e)
{
if(s.top-s.base>=STACK_INIT_SIZE)
{
s.base=(int*)malloc((STACK_INIT_SIZE+STACKINCREMENT)*sizeof(int));
if(!s.base)
exit(0);
s.top=s.base +s.stacksize;
s.stacksize +=STACKINCREMENT;
}
*s.top++=e;
}
//求栈中元素的个数
int StackLength(Sqstack s)
{
return s.top-s.base;
}
//删除栈顶元素
void pop(Sqstack &s, int &e)
{
if(s.top==s.base)
e=0;
else
e=*--s.top;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -