栈相关代码

Stack.h

//
//  Stack.hpp
//  FirstP
//
//  Created by 赫赫 on 2023/11/1.
//  这里主要记录一下顺序栈

#ifndef Stack_hpp
#define Stack_hpp
#define MaxSize 10

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>

#endif /* Stack_hpp */

typedef struct{
    int data[MaxSize];
    int top;//栈顶指针
}SqStack;

//初始化栈
void InitStack(SqStack &S);

//入栈
bool Push(SqStack &S,int elem);

//出栈
bool Pop(SqStack &S,int &elem);

//出栈
bool Pop(SqStack &S,char &elem);

//读栈顶元素
bool GetTop(SqStack &S,int &elem);

//用栈来实现表达式的括号匹配
bool bracketCheck(char str[],int length);

//---------------------------------
//共享栈的结构体定义
typedef struct{
    int data[MaxSize];
    int top0;//栈顶指针
    int top1;
}SqShareStack;

//初始化共享栈
void InitShareStack(SqShareStack &S);

Stack.cpp

//
//  Stack.cpp
//  FirstP
//
//  Created by 赫赫 on 2023/11/1.
//

#include "Stack.hpp"

//初始化栈
void InitStack(SqStack &S){
    S.top=-1;//初始化栈顶指针
}

//入栈
bool Push(SqStack &S,int elem){
    if(S.top==MaxSize-1){
        return false;
    }else{
        S.top+=1;
        S.data[S.top]=elem;
        return true;
    }
}

//出栈
bool Pop(SqStack &S,int &elem){
    if(S.top==-1){
        return false;
    }else{
        elem=S.data[S.top];
        S.top-=1;
        return true;
    }
}

bool Pop(SqStack &S,char &elem){
    if(S.top==-1){
        return false;
    }else{
        elem=S.data[S.top];
        S.top-=1;
        return true;
    }
}

//读栈顶元素
bool GetTop(SqStack &S,int &elem){
    if(S.top==-1){
        return false;
    }else{
        elem=S.data[S.top];
        return true;
    }
}

//用栈来实现括号表达式的匹配
bool bracketCheck(char str[],int length){
    SqStack S;
    InitStack(S);
    for(int i=0;i<length;i++){
        if(str[i]=='('||str[i]=='['||str[i]=='{'){
            Push(S,str[i]);
        }else{
            if(S.top==-1){//栈空
                return false;
            }
            char topElem;
            Pop(S,topElem);
            if(str[i]==')'&&topElem!='('){
                return false;
            }
            if(str[i]==']'&&topElem!='['){
                return false;
            }
            if(str[i]=='}'&&topElem!='{'){
                return false;
            }
        }
    }
    if(S.top==-1){//栈空
        return true;
    }else{
        return false;
    }
}

//初始化共享栈
void InitShareStack(SqShareStack &S){
    S.top0=-1;
    S.top1=MaxSize;
    //当top0+1=top1时共享栈满
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值