我们的教授要求我们使用堆栈来检查一个单词是否是回文。
每次运行它时,都会出现错误:Unhandled Exception。访问冲突
我做错了什么?我怎样才能改进我的代码?我的代码如下:
typedef struct stack{
char name;
struct stack * next;
}Stack;
void push(Stack**head, char value);
char pop(Stack**head);
int main(){
char word[11];
int i=0;
int lenght = 0;
Stack*head = NULL;
printf("Please type the word: ");
scanf("%s", word);
lenght = strlen(word);
while(word[i]!='\0'){
push(&head, word[i]);
i++;
}
i = 0;
while(pop(&head)==word[i]){
i++;
}
if(i==lenght) printf("The word is a palindrome");
else printf("The word is not a palindrome");
}
最佳答案
你的push
函数应该接受
- 栈头的地址(你是对的)和
- 需要压入的字符(这需要修复)。
所以方法签名变成:
void push(Stack**head, char value);
并在函数体中将 value
添加到堆栈顶部:
temp->name = value;
此外,您还必须始终检查 malloc
的返回值。
因为你从函数 pop
返回弹出的值,它的返回类型不能是 void
,在两个声明和定义为:
char pop(Stack**head)
还有一个逻辑错误:
首先,您将输入的所有字符压入堆栈。接下来你开始弹出字符。您的弹出没有终止条件。当您弹出所有字符(因此您的堆栈为空)时,下一次调用 pop
将导致崩溃,因为您将取消引用 NULL
指针( *head
将为 NULL
)。
为了解决这个问题,你只弹出你通过这样做推送的字符:
while(i<lenght && pop(&head)==word[i]){
由于 &&
是短路的,所以一旦弹出所有字符,pop
将不会被调用。
另一种方法(也是首选方法)是编写另一个名为 isEmpty
的函数,当堆栈为空时返回 true
/1
并使用它调用 pop
方法之前的方法。
关于c - 回文使用堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4426306/