栈也是线性表的一种,它描述了一种后入先出的操作,可以用顺序存储结构和链式存储结构实现
顺序栈的定义由两部分组成:
typedef struct{
ElemType data[MAX_SIZE]; //存储数据的数组
int top; //栈顶指针,它一开始指向-1
}SqStack;
sqstack.h如下:
#include <malloc.h>
#include <stdio.h>
#define MAX_SIZE 10
typedef int ElemType;
typedef struct{
ElemType data[MAX_SIZE];
int top;
}SqStack;
SqStack.cpp如下:
#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];
}
输出结果如下:
10 20 30 栈长度为:3
10 20 栈长度为:2
栈顶元素为:20