栈之顺序栈

栈也是线性表的一种,它描述了一种后入先出的操作,可以用顺序存储结构和链式存储结构实现
顺序栈的定义由两部分组成:

代码实现

1
2
3
4
typedef struct{
ElemType data[MAX_SIZE]; //存储数据的数组
int top; //栈顶指针,它一开始指向-1
}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
Author: 紫夜
Link: https://greedypirate.github.io/2017/07/14/栈之顺序表/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
支付宝打赏
微信打赏