|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- typedef char DataType;
- typedef struct node
- {
- DataType data;
- struct node *next;
- }linkstack,*link;
- int init(link top)
- {
- if(!top)
- {
- printf("申请内存失败!\n");
- return -1;
- }
- top->data='1';
- top->next=NULL;
- return 0;
- }
- int empty(link top)
- {
- if(top->next==NULL)
- return 1;
- else return 0;
- }
- int push(link top,DataType e)
- {
- link p=(link)malloc(sizeof(linkstack));
- if(!p)
- {
- printf("申请空间失败!\n");return -1;
- }
- p->data=e;
- p->next=top->next;
- top->next=p;
- return 0;
- }
- int gettop(link top,DataType *e)
- {
- link p;//
- if(empty(top))
- {
- printf("栈是空的!\n");
- return -1;
- }
- p=top->next;
- *e=p->data;
- return 0;
- }
- int pop(link top,DataType *e)
- {
- if(empty(top))
- {
- printf("栈是空的!\n");
- return -1;
- }
- link p;
- p=top->next;
- *e=p->data;
- top->next=p->next;
- free(p);
- return 0;
- }
- int destroy(link top)
- {
- if(!top)
- {
- printf("栈是空的!\n");
- return -1;
- }
- link p,q;
- p=top;
- while(!p)
- {
- q=p;
- p=p->next;
- free(q);
- }
- return 0;
- }
- int match(DataType a,DataType b)
- {
- if(a=='('&&b==')')
- return 1;
- else if(a=='['&&b==']')
- return 1;
- else if(a=='{'&&b=='}')
- return 1;
- else
- return 0;
- }
- int main()
- {
- char s[60];
- printf("请输入表达式:");
- gets(s);
- char *pp=s;char *q;
- link top=(link)malloc(sizeof(linkstack));
- init(top);
- while(*pp)
- {
- switch(*pp)
- {
- case'(':
- case'[':
- case'{':push(top,*pp);break;
- case')':
- case']':
- case'}':if(empty(top)) {
- printf("括号不匹配!\n");return -1;
- }
- gettop(top,q);
- if(match(*q,*pp)) pop(top,q);
- else
- {
- printf("括号不匹配!\n");
- return -1;
- }break;
- }
- pp++;
- }
- if(empty(top)) printf("括号匹配!\n");
- return 0;
- }
复制代码
本来是个简单的判断表达式括号是否匹配的程序,但是一运行就出错,调试发现是在扫描到右括号的时候用gettop函数,发现top->next被认为是NULL?我明明前面有push操作啊?是不是我的gettop函数写的有问题?求各位大神解答,感激不尽!
指针是一个变量,一个保存地址的变量
char a = '\n';
char *q = &a; // q是一个变量,这个变量中保存了一个地址,保存了变量a的地址
char q; // q是一个变量,这个变量中保存一个字符,&q 得到变量q的地址
|
|