# include <stdio.h> # include <stdlib.h> # include "stack.h" typedef int datatype; int isSymmeric_stack (){ seqstack*s= (seqstack*)malloc(sizeof(seqstack)); setnull(s); int i=0,len = (s->top+1),isSymmetric = 0; seqstack*p=(seqstack*)malloc(sizeof(seqstack)); setnull(p); for(i;i<len/2;i++){ push(p,s->data[s->top]); s->top--; } if (len%2==1){ s->top--; } while (pop(p)==s->data[s->top]){ s->top--; if(s->top==-1) { isSymmetric=1; break; } } return isSymmetric; } int main(){ datatype c,isSymmetric = 0; seqstack*s; s=(seqstack*)malloc(sizeof(seqstack)); setnull (s); c =getchar(); while (c!='*'){ push(s,c); c=getchar(); } printf("%d\n",isSymmetric_stack(s)); return 0; }
时间: 2023-12-02 11:03:25 浏览: 76
这段代码存在问题,因为在函数`isSymmeric_stack()`中,栈`s`是空栈,所以`s->top`的值为-1,而此时计算长度`len`的值为0,导致后续代码无法正确执行。同时,函数中使用了两个栈`s`和`p`,但是`s`栈在函数中没有被使用,因此可以直接在主函数中定义并传递给函数。此外,函数中需要释放`malloc`分配的内存。以下是修改后的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
typedef int datatype;
int isSymmetric_stack(seqstack *s) {
seqstack *p = (seqstack*)malloc(sizeof(seqstack));
setnull(p);
int i = 0, len = (s->top + 1), isSymmetric = 0;
for (i; i < len/2; i++) {
push(p, s->data[s->top]);
s->top--;
}
if (len % 2 == 1) {
s->top--;
}
while (pop(p) == s->data[s->top]) {
s->top--;
if (s->top == -1) {
isSymmetric = 1;
break;
}
}
free(p);
return isSymmetric;
}
int main() {
datatype c;
seqstack *s = (seqstack*)malloc(sizeof(seqstack));
setnull(s);
c = getchar();
while (c != '*') {
push(s, c);
c = getchar();
}
printf("%d\n", isSymmetric_stack(s));
free(s);
return 0;
}
```
阅读全文