#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;
}