美好的一天! 我们的老师要求我们确定一个单词或一系列数字是否是回文或不使用堆栈。我已经完成了。但我现在想更多地练习,我试图通过删除空格和其他不相关的字符来确定句子是否是回文。(注意:不再是我家庭作业的一部分)我的代码已经工作(希望),但是我发现它凌乱。所以我想改善它。我想删除goto函数,因为我的老师建议我不要使用它。我如何使用goto函数离开if语句?先谢谢你。还有其他方法可以检查句子是否是回文,因为我的代码是用暴力方法完成的。我的代码如下:注意(我没有包含/粘贴的结构,并在弹出这里推送功能)从您的建议基于回文 - 删除转到
int main(){
char word[11];
char temp[11];
char value;
int i=0, x=0, n=0, length=0;
Stack*head = NULL;
printf("Please type the word: ");
gets(word);
length = strlen(word);
while(i<length){
if(isspace(word[i]) || !isalpha(word[i])) {
if(isdigit(word[i])) goto NEXT; // i used the goto function here
i++;
continue;
}
NEXT:
temp[n]=word[i];
push(&head, word[i]);
i++;
n++;
}
temp[n]='\0';
while(x<n){
value = pop(&head);
if (value==temp[x]){
x++;
continue;
}
break;
}
if(x==n) printf("Yehey! It is a palindrome.");
else printf("Sorry, It is not a palindrome.");
getch();
}
。这里是我的改进代码:
int main(){
char word[11];
char temp[11];
int i=0, n=0;
int flag = 1;
Stack*head = NULL;
printf("Please type the word: ");
fgets(word, 11, stdin);
for(i = 0; word[i]!='\0' ; i++){
if(isalnum(word[i])) {
temp[n]=word[i];
push(&head, word[i]);
n++;
}
}
temp[n]='\0';
for(i=0; temp[i]!='\0'; i++){
if (pop(&head)!=temp[i]){
flag = 0;
break;
}
}
if (flag==1) printf("Yehey! It is a palindrome.");
else printf("Sorry, It is not a palindrome.");
getch();
}
我也建议你停止使用得到()函数。使用fgets()代替,所以如果你输入11个或更多字符,你不会粉碎你的堆栈。 – BatchyX 2010-12-13 13:08:10