数据结构学习日记(2)——用栈实现括号匹配

来源:互联网 发布:淘宝买书靠谱吗 编辑:程序博客网 时间:2024/06/06 02:28

关于怎么用代码写一个栈可以看我的数据结构学习日记(1),这里就用那里写下的栈来作为栈类型

#include "MyStack.h"#include <iostream>using namespace std;int main(){           MyStack<char> *pstack = new MyStack<char>(40);    MyStack<char> *NeedPstack = new MyStack<char>(40);    char str[] = "[()]}";    char currentNeed = NULL;    for (int i(0); i < strlen(str); ++i)    {        if (str[i] != currentNeed)        {            pstack->push(str[i]);            switch (str[i])            {            case '[':                if (currentNeed != 0)                {                    NeedPstack->push(currentNeed);                }                currentNeed = ']';                break;            case '{':                if (currentNeed != 0)                {                    NeedPstack->push(currentNeed);                }                currentNeed = '}';                break;            case '(':                if (currentNeed != 0)                {                    NeedPstack->push(currentNeed);                }                currentNeed = ')';                break;            default:                cout << "不匹配" << endl;                system("pause");                return 0;                           }        }        else        {            char elem;            pstack->pop(elem);            if (!NeedPstack->pop(currentNeed))            {                currentNeed=NULL;            }        }    }    if (pstack->stackEmpty())    {        cout << "匹配" << endl;    }    else        cout << "不匹配" << endl;    delete pstack;    delete NeedPstack;    pstack = NULL;    system("pause");    return 0;}
阅读全文
0 0
原创粉丝点击