数据结构--栈--线性存储
栈就是后进先出,从代码实现来看跟线性表是一样的,只是进出数据的方式不同。如果要进行复杂操作,内部用线性表的操作方式就可以。
编译器:GCC
#include <stdio.h> typedef int elemType; struct stack{ elemType *stack; /*存储栈元素的数组指针*/ int top; /*存储栈顶元素的下标位置*/ int maxsize; /*存储stack数组的长度*/ }; /* 1.初始化栈s为空*/ void initStack(struct stack *s,int ms) { s->stack = malloc(ms * sizeof(elemType)); if(s->stack == NULL) { printf("空间申请失败...\n"); system("pause"); } s->top = -1; s->maxsize = ms; return; } /* 2.扩展栈空间为原来的两倍*/ void againMalloc(struct stack *s) { elemType *p; p = (elemType *)realloc(s->stack, 2 * s->maxsize * sizeof(elemType)); if(p == NULL) { printf("空间申请失败...\n"); system("pause"); } s->stack = p; s->maxsize = 2 * s->maxsize; return; } /* 3.新元素进栈,即把它插入到栈顶*/ void push(struct stack *s, elemType x) { if(s->top == s->maxsize) { againMalloc(s); } s->stack[++s->top]=x; return; } /* 4.删除(弹出)栈顶元素并返回其值*/ elemType pop(struct stack *s) { if(s->top == -1) { printf("栈空,弹出失败...\n"); system("pause"); } elemType data = s->stack[s->top]; s->top-=1; return data; } /* 5.读取栈顶元素的值*/ elemType peek(struct stack *s) { if(s->top == -1) { printf("栈空,弹出失败...\n"); system("pause"); } return s->stack[s->top]; } /* 6.判断s是否为空,若是返回1,否则返回0*/ int emptyStack(struct stack *s) { if(s->top == -1) { return 1; }else{ return 0; } } /* 7.清除栈s中的所有原色,释放动态存储空间*/ void clearStack(struct stack *s) { free(s->stack); s->stack=NULL; s->top=-1; s->maxsize=0; return; } /*******************************************************/ int main(void) { struct stack s; int a[8] = {3,8,5,17,9,30,15,22}; int i; initStack(&s, 5); printf("初始化栈...\n"); for(i=0; i<8; i++) { printf("%d ",a[i]); push(&s, a[i]); } printf("\n操作顺序:pop pop push(68) pop pop \n"); printf("%d ",pop(&s)); printf("%d ",pop(&s)); push(&s, 68); printf("%d ",pop(&s)); printf("%d ",pop(&s)); printf("\npop出剩余的...\n"); while(!emptyStack(&s)) { printf("%d ", pop(&s)); } printf("\n"); clearStack(&s); system("pause"); return 0; }
****************************************************************************
运行结果:
****************************************************************************
初始化栈... 3 8 5 17 9 30 15 22 操作顺序:pop pop push(68) pop pop 22 15 68 30 pop出剩余的... 9 17 5 8 3 请按任意键继续. . .