问题:假设一个算术表达式中包括圆括号,方括号和花括号3种类型的括号,编写程序判别表达式中括号是否配对
顺序栈
顺序栈要求输入的最大数量小于其最大容量,防止出现上溢出的情况;
顺序栈的建立和入栈,出栈的C++实现:
#include <iostream> #define M 50 using namespace std; typedef struct { char data[M]; int top=-1; }stack; void init(stack& s) { //初始化,输入数值,输入负数结束 char x; s.top = -1; cin >> x; do { s.data[++s.top] = x; cin >> x; if (s.top == M - 1) { cout << "full room" << endl; return; } } while (x!='~'); } void dis(stack s) { //输出栈的数值 while (s.top != -1) { cout << s.data[s.top--]<<" "; } cout << endl; } void push(stack& s, char x) //入栈 { if (s.top == M - 1) { cout << "full room" << endl; return; } s.data[++s.top] = x; } void pop(stack& s) //出栈 { if (s.top == -1) { cout << "empty" << endl; return; } cout<<"pop: "<<s.data[s.top--]<<endl; } void ifleg(stack s) //判断输入的({{符号是否符合语法 { char x; cin >> x; do { if (x == '(' || x == '[' || x == '{') //左符号直接进栈 push(s, x); else if (x == ')') //右符号若和栈顶字符匹配就直接消除 //不匹配报错 { if (s.top == -1) return; if (s.data[s.top] == '(') s.top--; else { cout << "error" << endl; return; } } else if (x == ']') { if (s.top == -1) return; if (s.data[s.top] == '[') s.top--; else { cout << "error" << endl; return; } } else if (x == '}') { if (s.top == -1) return; if (s.data[s.top] == '{') s.top--; else { cout << "error" << endl; return; } } cin >> x; } while (x != '~'); //输入~后终止输入 if (s.top != -1)//终止输入后栈不空则也是不合语法的,有没匹配的字符 { cout << "error" << endl; return; } else { cout << "stack is empty , finish" << endl; } } int main(void) //通过栈判断一个字符串是不是回文字符串 { stack s; ifleg(s); }
输入输出:( ( { [ { } ] } ) )
输入输出:( { [ }
输入输出:{ ( ) } { { }
链式栈
相比于顺序栈,链式栈的优点是便于多个栈共享存储空间提高存储其效率,不会发生栈的上溢出情况;
链式栈的建立,入栈,出栈的C++实现:
#include <iostream> #define M 50 using namespace std; typedef struct LNode{ char data; struct LNode* next; }LNode,*ListStack; void Init(ListStack& s) //涉及到修改s的内容时加引用号&,其他情况不需要 //采用链表的头插法实现入栈 { char x; s->next = NULL; cin >> x; do { LNode* l=(LNode*)malloc(sizeof(LNode));//申请新的结点 l->data = x; l->next = s->next; s->next = l; cin >> x; } while (x != '~'); } void push(ListStack& s, char x) //入栈,头插法 { LNode* l = (LNode*)malloc(sizeof(LNode)); l->data = x; l->next = s->next; s->next = l; cout << "入栈 :" << x << endl; } void pop(ListStack& s)//出栈 { LNode* l = (LNode*)malloc(sizeof(LNode)); l = s->next; s->next = l->next; cout << "出栈:" << l->data << endl; free(l); } void dis(ListStack s)//输出栈的数据 { while (s->next!= NULL) { s = s->next; cout << s->data << " "; } cout << endl; } int main(void) { ListStack s=(ListStack)malloc(sizeof(LNode));//为栈申请一个头结点空间 Init(s);//初始化并赋值 dis(s); push(s,'x');//x入栈 dis(s); pop(s);//相继弹出栈的两个元素 pop(s); dis(s); }
原文链接: https://www.cnblogs.com/murenma/p/13303383.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/366354
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!