C语言用栈写一个判断输入的表达式的括号是否正确的算法?表达式中包含两种括号,圆括号和方括号.会的朋友帮忙写下.二楼的哥们,栈是老师要求的,原来根本没学过如何实用栈
来源:学生作业帮助网 编辑:作业帮 时间:2024/07/30 18:33:55
![C语言用栈写一个判断输入的表达式的括号是否正确的算法?表达式中包含两种括号,圆括号和方括号.会的朋友帮忙写下.二楼的哥们,栈是老师要求的,原来根本没学过如何实用栈](/uploads/image/z/22742-62-2.jpg?t=C%E8%AF%AD%E8%A8%80%E7%94%A8%E6%A0%88%E5%86%99%E4%B8%80%E4%B8%AA%E5%88%A4%E6%96%AD%E8%BE%93%E5%85%A5%E7%9A%84%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9A%84%E6%8B%AC%E5%8F%B7%E6%98%AF%E5%90%A6%E6%AD%A3%E7%A1%AE%E7%9A%84%E7%AE%97%E6%B3%95%3F%E8%A1%A8%E8%BE%BE%E5%BC%8F%E4%B8%AD%E5%8C%85%E5%90%AB%E4%B8%A4%E7%A7%8D%E6%8B%AC%E5%8F%B7%2C%E5%9C%86%E6%8B%AC%E5%8F%B7%E5%92%8C%E6%96%B9%E6%8B%AC%E5%8F%B7.%E4%BC%9A%E7%9A%84%E6%9C%8B%E5%8F%8B%E5%B8%AE%E5%BF%99%E5%86%99%E4%B8%8B.%E4%BA%8C%E6%A5%BC%E7%9A%84%E5%93%A5%E4%BB%AC%2C%E6%A0%88%E6%98%AF%E8%80%81%E5%B8%88%E8%A6%81%E6%B1%82%E7%9A%84%2C%E5%8E%9F%E6%9D%A5%E6%A0%B9%E6%9C%AC%E6%B2%A1%E5%AD%A6%E8%BF%87%E5%A6%82%E4%BD%95%E5%AE%9E%E7%94%A8%E6%A0%88)
C语言用栈写一个判断输入的表达式的括号是否正确的算法?表达式中包含两种括号,圆括号和方括号.会的朋友帮忙写下.二楼的哥们,栈是老师要求的,原来根本没学过如何实用栈
C语言用栈写一个判断输入的表达式的括号是否正确的算法?
表达式中包含两种括号,圆括号和方括号.会的朋友帮忙写下.
二楼的哥们,栈是老师要求的,原来根本没学过如何实用栈
C语言用栈写一个判断输入的表达式的括号是否正确的算法?表达式中包含两种括号,圆括号和方括号.会的朋友帮忙写下.二楼的哥们,栈是老师要求的,原来根本没学过如何实用栈
//---------------------------------------------------------------------------
#include
#include
#define MEM_ERR "malloc() error!"
#define EMPTY_ERR "stack is empty!"
typedef struct node{
char oper;
struct node *next;
}node;
typedef struct{
node *head;
unsigned int size;
}stack;
void error_exit(const char *msg)
{
fprintf(stderr,"%s\n",msg);
exit(-1);
}
int isempty(stack *stk)
{
return stk->size?0:1;
}
stack *init(void)
{
stack *rt=(stack*)malloc(sizeof(stack));
if (rt==NULL) error_exit(MEM_ERR);
rt->head=NULL;
rt->size=0;
return rt;
}
void push(stack *stk,char op)
{
node *tp=(node*)malloc(sizeof(node));
if (tp==NULL) error_exit(MEM_ERR);
tp->oper=op;
tp->next=stk->head;
stk->head=tp;
++stk->size;
}
char pop(stack *stk)
{
char op;
node *tmp;
if (isempty(stk)) {
error_exit(EMPTY_ERR);
}
op=stk->head->oper;
tmp=stk->head;
stk->head=tmp->next;
--stk->size;
free(tmp);
return op;
}
char top(stack *stk)
{
if (isempty(stk)) {
error_exit(EMPTY_ERR);
}
return stk->head->oper;
}
void del_stk(stack *stk)
{
node *t;
while (stk->head)
{
t=stk->head;
stk->head=t->next;
free(t);
}
free(stk);
}
int islr(const char a)
{
return a=='('||a=='['||a=='{';
}
int isrr(const char a)
{
return a==')'||a==']'||a=='}';
}
int match(const char a,const char b)
{
int t;
switch (a) {
case '(':t=b==')';break;
case '[':t=b==']';break;
case '{':t=b=='}';break;
}
return t;
}
int main(int argc,char* argv[])
{
char a;
stack *stk=init();
while ((a=getchar())!='\n')
{
if (islr(a)) {
push(stk,a);
}
else if (isrr(a)) {
if (!isempty(stk)&&match(top(stk),a)) pop(stk);
else break;
}
}
if (!isempty(stk)) {
printf("Unmatched!\n");
del_stk(stk);
}
else printf("Matched!\n");
return 0;
}
//---------------------------------------------------------------------------