堆栈应用——括号匹配

#include <iostream>
#include <string>
#include "mystack.h"
using namespace std;
int main()
{
    stack s;
    int f = 1;
    string str;
    getline(cin,str);//支持空格,cin读到空格停止
    for (int i = 0; i < str.length(); i++)
    {
        if (str[i] == '(' || str[i] == '[' || str[i] == '{')
        {
            s.mypush(s, str[i]);
        }
        else if (str[i] == ')' || str[i] == ']' || str[i] == '}')
        {           
            if (s.top->next)
            {
                char c = (s.top)->next->data;
                if ((c == '(' && str[i] == ')') || (c == '[' && str[i] == ']') || (c == '{' && str[i] == '}'))
                    s.mypop(s);
                else
                {
                    f = 0;
                    cout << "不匹配诶~" << endl;
                }
            }
            else
            {
                f = 0;
                cout << "右边落单了诶~" << endl;
            }
        }
    }
    if (s.top->next != NULL)
    {
        if (f)
        {
            f = 0;
            cout << "左边落单了诶~" << endl;
        }
    }
    else
    {
        if (f)
        {
            cout << "耶耶耶!" << endl;
        }
    }
}

头文件代码 

#pragma once
#include <iostream>
using namespace std;
typedef char elem;
typedef struct node
{
    elem data;
    node* next;
};
class stack
{
public:
    int size;
    node* top;//栈顶指针
    stack()
    {
        size = 0;
        top = new node;
        top->next = NULL;
    }
    ~stack()
    {
        size = 0;
        node* p = top;
        while (p->next)
        {
            p = top->next;
            delete top;
            top = p;
        }
    }
    void mypush(stack& s, elem e);
    elem mypop(stack& s);
};
void stack::mypush(stack& s, elem e)
{
    node* p = new node;
    p->data = e;
    p->next = top->next;
    top->next = p;
    size++;
}
elem stack::mypop(stack& s)
{
    size--;
    node* p = top->next;
    elem d = p->data;
    top->next = p->next;
    delete p;
    return d;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值