栈是仅在表尾进行插入、删除操作的线性表。即栈 S= (a1, a2, a3, ………,an-1, an)
,其中表尾称为栈顶 /top
,表头称为栈底/base
。
因为只能在表尾进行操作,因而栈的运算规定就是“后进先出”(LIFO)
和线性表相似,栈也有两种存储构造——程序栈与链栈
1.程序栈的C语言实现
#include <stdio.h>#include <stdlib.h>typedef struct Stack { int *data;//数据域 int size;//栈长度,也是栈顶数组下标-1 int max;//栈最大容量} Stack;//初始化Stack *initStack(int max){ struct Stack *stack; stack = (struct Stack *)malloc(sizeof(struct Stack)); stack->size = 0; stack->max = max; stack->data = (int*)malloc(sizeof(int)*max); return stack;}//压栈void push(Stack *stack, int item){ if (stack->size >= stack->max) { printf("stack is full! \n"); }else{ stack->data[stack->size++] = item; } }//出栈int pop(Stack *stack){ if (stack->size >= 0) { return stack->data[--stack->size]; }}//testint main(){ struct Stack *stack; stack = initStack(3); push(stack,1); push(stack,2); push(stack,3); push(stack,4); printf("stack out:%d \n", pop(stack)); printf("stack out:%d \n", pop(stack)); push(stack,5); push(stack,6); push(stack,7); printf("stack out:%d \n", pop(stack)); printf("stack out:%d \n", pop(stack)); printf("stack out:%d \n", pop(stack)); return 0;}
测试成果:
Todo:
- [ ] 链栈的C语言实现