栈
栈也是线性表的一种,它描述了一种后入先出的操作,可以用顺序存储结构和链式存储结构实现
顺序栈的定义由两部分组成:
代码实现
1 2 3 4
| typedef struct{ ElemType data[MAX_SIZE]; int top; }SqStack;
|
sqstack.h如下:
1 2 3 4 5 6 7 8 9 10
| #include <malloc.h> #include <stdio.h>
#define MAX_SIZE 10 typedef int ElemType;
typedef struct{ ElemType data[MAX_SIZE]; int top; }SqStack;
|
SqStack.cpp如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include "sqstack.h"
void initStack(SqStack *&stack); void destoryStack(SqStack *&stack); int getLength(SqStack *stack); void printStack(SqStack *stack); bool isEmpty(SqStack *stack);
bool push(SqStack *&stack, ElemType e); bool pop(SqStack *&stack, ElemType &e); ElemType peek(SqStack *stack); int main() { SqStack *stack; initStack(stack);
push(stack,10); push(stack,20); push(stack,30); printStack(stack); printf("栈长度为:%d\n",getLength(stack));
ElemType e; pop(stack,e); printStack(stack); printf("栈长度为:%d\n",getLength(stack));
e = peek(stack); printf("栈顶元素为:%d",e); return 0; }
void initStack(SqStack *&stack){ stack = (SqStack *) malloc(sizeof(SqStack)); stack->top = -1; }
void destoryStack(SqStack *&stack){ free(stack); }
int getLength(SqStack *stack){ return (stack->top + 1) ; } bool isEmpty(SqStack *stack){ return stack->top == -1; }
void printStack(SqStack *stack){ int i; for(i = 0; i<=stack->top; i++){ printf("%d\t",stack->data[i]); } }
bool push(SqStack *&stack, ElemType e){ if(stack->top+1 == MAX_SIZE){ printf("栈满,无法入栈\n"); return false; } stack->top++; stack->data[stack->top] = e; return true; } bool pop(SqStack *&stack, ElemType &e){ if(stack->top == -1){ printf("栈空,无可出栈元素"); return false; } e = stack->data[stack->top]; stack->top--; return true; }
ElemType peek(SqStack *stack){ return stack->data[stack->top]; }
|
输出结果
1 2 3
| 10 20 30 栈长度为:3 10 20 栈长度为:2 栈顶元素为:20
|