栈——顺序栈

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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值