数据结构实验:栈的基本操作
发布网友
发布时间:2022-04-29 10:36
我来回答
共1个回答
热心网友
时间:2022-05-18 15:18
#include<iostream>
using namespace std;
class Stack
{
public:
int size;
int top;
char *stack;
Stack(int m);
bool push(char item);//入栈
bool pop();//出栈
bool isempty();//是否为空
void clear();//清空栈
int Size();//栈中元素个数
~Stack();
char Top();
};
#include<iostream>
#include"Stack.h"
using namespace std;
Stack::Stack(int m){
top=-1;
stack=new char[m];
size = 0;
}
void Stack::clear(){
delete []stack;
size = 0;
stack=NULL;
}
Stack::~Stack(){
clear();
}
bool Stack ::push(char item){
top++;
stack[top]=item;
size++;
return true;
}
bool Stack::isempty(){
if(stack == NULL)
return true;
else
return false;
}
bool Stack::pop(){
if(isempty()){
cout<<"栈为空,不能执行出栈操作!"<<endl;
return false;
}
else{
top--;
size--;
return true;
}
}
int Stack::Size(){
return size;
}
char Stack::Top()
{
return stack[top];
}
#include<iostream>
#include"Stack.h"
using namespace std;
int main()
{
Stack s(20);
char a[50];
char *st = a;
int b=0;
cout<<"请输入你要检查的字符串:"<<endl;
cin>>a;
while((*st)!='\0'){b++;
if((*st) == '('||(*st) == '{'||(*st) == '['){
cout<<endl;
cout<<*st<<" 为分隔符左半边"<<endl;
s.push((*st));
}
else if((*st) == '/'&&(*(st+1)) == '*'){
cout<<endl;
cout<<*st<<*(st+1)<<" 为分隔符左半边"<<endl;
s.push((*st));
s.push(*(st+1));
}
else if((*st) == ')'||(*st) == '}'||(*st) == ']'){
if(((*st) ==')'&& (s.Top() =='('))||((*st) =='}'&& (s.Top() =='{'))||((*st) ==']'&& (s.Top() =='['))){
cout<<*st<<" 为分隔符右半边"<<endl;
s.pop();
cout<<"匹配"<<endl;
cout<<endl;}
else {
cout<<*st<<" 为分隔符右半边"<<endl;
cout<<"但 "<<(*st)<<"不匹配"<<endl;
cout<<"第"<<b<<"位"<<endl<<endl;
}
}
else {if((*st) == '*'&&(*(st+1)) == '/'){
if(((*st)=='*')&&((s.Top())=='*')&&((*(st+1))=='/')){
cout<<*st<<*(st+1)<<" 为分隔符左半边"<<endl;
s.pop();
s.pop();
cout<<"匹配"<<endl;}
else{
cout<<*st<<*(st+1)<<" 为分隔符右半边"<<endl;
cout<<"但 "<<(*st)<<*(st+1)<<"不匹配"<<endl;
cout<<"第"<<b<<"位"<<endl<<endl;
}
}
}
st++;
}
if(s.size == 0){
cout<<"====================================="<<endl;
cout<<"分隔符匹配正确!"<<endl;
cout<<"====================================="<<endl;}
else
{
cout<<"====================================="<<endl;
cout<<"分隔符不匹配,请检查输入字符!"<<endl;
cout<<"====================================="<<endl;
}
return 0;
}
自己编的,复杂版,可以检查{}()【】/* */等符号的匹配
你看看有用不