数据结构 第二章栈队列和数组

一、栈

n个不同元素进栈,出栈元素不同排列的个数为\frac{1}{n+1}C_{n}^{2n}

栈的顺序存储

#include <iostream>
using namespace std;
typedef int ElemType;
#define MaxSize 50
typedef struct
{
    ElemType data[MaxSize];
    int top;
}SqStack;
//初始化
void InitStack(SqStack &s)
{
    s.top=-1;
}
//判空
bool StackEmpty(SqStack s)
{
    if(s.top==-1)
        return true;
    return false;
}
//进栈
bool Push(SqStack &s,ElemType x)
{
    if(s.top==MaxSize-1)
        return false;
    s.data[++s.top]=x;
    return true;
}
//出栈
bool Pop(SqStack &s,ElemType &x)
{
    if(StackEmpty(s))
    return false;
    x=s.data[s.top--];
    return true;
}
//读栈顶元素
bool GetTop(SqStack s,ElemType &x)
{
    if(StackEmpty(s))
        return false;
    x=s.data[s.top];
    return true;
}
int main()
{
    SqStack s;
    InitStack(s);
    Push(s,10);
    ElemType y=1;
    GetTop(s,y);
    cout<<y;
    return 0;
}

栈的链式存储

二、队列

数组a[n]的下标范围为0~n-1。若写成a[0...n]说明下标范围为0~n;

队列的顺序存储

队列的链式存储

三、栈和队列的应用

栈:括号匹配

请输入英文括号

#include <iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef char ElemType;
#define MaxSize 50
typedef struct
{
    ElemType data[MaxSize];
    int top;
}SqStack;
//初始化
void InitStack(SqStack &s)
{
    s.top=-1;
}
//判空
bool StackEmpty(SqStack s)
{
    if(s.top==-1)
        return true;
    return false;
}
//进栈
bool Push(SqStack &s,ElemType x)
{
    if(s.top==MaxSize-1)
        return false;
    s.data[++s.top]=x;
    return true;
}
//出栈
bool Pop(SqStack &s,ElemType &x)
{
    if(StackEmpty(s))
    return false;
    x=s.data[s.top--];
    return true;
}
//读栈顶元素
bool GetTop(SqStack s,ElemType &x)
{
    if(StackEmpty(s))
        return false;
    x=s.data[s.top];
    return true;
}
bool work(char ss[])
{
    SqStack s;
    InitStack(s);
    int length=strlen(ss);
     for(int i=0;i<length;i++)
    {
        if(ss[i]=='('||ss[i]=='[')
        {
            Push(s,ss[i]);
        }
        else
        {
            char q;
            Pop(s,q);
            if(ss[i]==')'&&q!='(')
                return false;
            if(ss[i]==']'&&q!='[')
                return false;

        }
    }

    return StackEmpty(s);
}
int main()
{

    char ss[MaxSize];
    scanf("%s",ss);
    if(work(ss))
        printf("成功");
    else printf("失败");
    return 0;
}

栈:表达式求值

中缀表达式转化为后缀表达式

中缀转化为前缀表达式

栈:递归

队列:树或图的广度优先遍历(宽搜)

队列:操作系统中的先来先服务,打印缓冲区

四、数组和特殊矩阵

  • 15
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值