1.栈的元素必须后进先出 2.栈的操作只能在线性表的表尾进行 3.对于栈,栈的表尾称为栈顶(top),相应的表头称为栈底(bottom)。 栈的插入操作(push)叫进栈,也叫压栈,入栈。 栈的删除操作(Pop),叫出栈,也叫弹栈。 //栈基本操作 //栈的顺序存储结构 #define STACK_INIT_SIZE 100 typedef struct { ElemType *base; //base是指向栈底的指针变量 ElemType *top; //top是指向栈顶的指针变量 int stackSize; //stackSize指示栈的当前可使用的最大容量 }sqStack; //初始化 initStack(sqStack *s) { s->base = (ElemType *)malloc(STACK_INIT_SIZE*(ElemType)); if(!s->base) exit(0); s->top = s->base; //最开始栈顶就是栈底 s->stackSize = STACK_INIT_SIZE; } //入栈 每次向栈中压入一个数据,top指针+1,直到栈满为止 #define SATCKINCREMENT 10 //增量 Push(sqStack *s,ElemType e) { //如果栈满,追加空间 if(s->top - s->base >= s->stackSize) { s->base = realloc(s->base,(s->stackSize+SATCKINCREMENT)*sizeof(ElemType));//相当于扩容 if(!s->base) exit(0); s->top = s->base+s->stackSize; //设置栈顶 s->stackSize = s->stackSize + SATCKINCREMENT;//设置栈的最大容量 } *(s->top) = e; s->top++; } //出栈操作 //出栈操作就是在栈顶取出数据,栈顶指针随之下移的操作 //每次弹出一个数据,栈的当前容量就-1 Pop(sqStack *s, ElemType *e) { if(s->top == s->base) //栈已经是空空如也 return; *e = *--(s->top); //top指针是栈顶 实质是没有数据的所一需要先自减才能取出数据 } //清空一个栈 物理空间不会改变 ClearStack(sqStack *s) { s->top = s->base; } //销毁栈 清除物理空间 DestoryStack(sqStack *s) { int i,len; len = s->stackSize; //获取容量 for(i = 0; i < len; i++) { free(s->base); s->base++; } s->base = s->top = NULL; s->stackSize = 0; } //计算栈的当前容量 int Stacklen(sqStack s) { return(s.top - s.base); } //顺序栈的基本操作 (在下亲自编写) #include<stdio.h> #include<stdlib.h> #define OK 1 #define OVERFLOW -1 #define ERROR -1 #define MAXSIZE 100 typedef int ElemType; typedef int Status; typedef int SElemType; typedef struct { SElemType *base; //栈底指针 SElemType *top; //栈顶指针 int stacksize; }SqStack; Status InitStack(SqStack *s); //初始化 Status Push(SqStack *s,SElemType e); //压栈 Status StackLen(SqStack s); //测量 SElemType GetTop(SqStack s); //获取顶部元素 Status Pop(SqStack *s,SElemType *e); //出栈 Status InitStack(SqStack *s) { s->base = (SElemType *)malloc(MAXSIZE*sizeof(SElemType)); if(!s->base) //储存分配失败 { exit(OVERFLOW); } s->top = s->base; //空栈 s->stacksize = MAXSIZE; return OK; } Status Push(SqStack *s,SElemType e) { if(s->top - s->base >= s->stacksize) return ERROR; *(s->top)++ = e;//压入栈顶 栈顶指针加1 return OK; } Status StackLen(SqStack s)//测量 { return (s.top - s.base); } Status Pop(SqStack *s,SElemType *e) { if(s->top == s->base) { return ERROR; } *e = *--(s->top); return OK; } SElemType GetTop(SqStack s) { if(s.top != s.base) //栈为非空 return *(s.top-1); } int main(void) { SqStack s; SElemType e; ElemType len; ElemType i; SElemType data; InitStack(&s); //栈的初始化 printf("请输入数据,以0结束!\n"); while(1) //入栈 { scanf("%d",&e); if(e == 0) break; Push(&s,e); } len = StackLen(s);//测量 printf("栈的长度为:%d",len); printf("\n\n"); data = GetTop(s); printf("栈顶的元素为:%d",data); printf("\n\n"); printf("栈中的数据为:\n"); for(i=0; i < len; i++) { Pop(&s,&e); //出栈 printf("%4d",e); } return 0; }
来源:https://www.cnblogs.com/ZhengLijie/p/12491245.html