我遇到了这个问题,我需要为其创建一个代码。所以我们有一个由用户输入的字符串,然后代码需要检查该句子是否是回文(句子中间的对称词应该相同。但是我们应该使用堆栈来实现这一点。 我熟悉函数 pop() 和 push() (尽管我在下面没有使用过它们)。到目前为止我所想的是,我获取字符串并从该字符串中创建一个单词堆栈,然后使用该堆栈来检查该句子是否是回文。我现在被困住了,我真的想不出别的事情了。非常感谢您的帮助。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
char s[30];
struct stack *next;
};
typedef struct stack STACK;
struct top
{
int num;
struct stack *top;
};
typedef struct top TOP;
void create_stack(TOP *s, char str[1000])
{
char temp1[30];
int i=0, j=0;
STACK *temp;
temp=(STACK*)malloc(1*sizeof(STACK));
while(1)
{
if(str[i]!=' ' && str[i]!='\0')
{
temp1[j]=str[i];
j++;
}
else
{
temp1[j]='\0';
strcpy(temp->s,temp1);
printf("%s\n", temp->s);
if(s->top==NULL)
{
s->top=temp;
s->num=1;
}
else
{
temp->next=s->top;
s->top=temp;
s->num++;
}
j=0;
}
if(str[i]=='\0')
{
break;
}
i++;
}
}
void move_cursor(STACK *cursor, int pos)
{
while (pos!=0)
{
cursor=cursor->next;
pos--;
}
}
void compare(TOP *s)
{
STACK *cursor1, *cursor2;
cursor1=s->top;
cursor2=s->top;
int cursor_move1, cursor_move2, i=0, check=1;
if(s->num%2==0)
{
cursor_move1=s->num/2;
cursor_move2=(s->num/2)+1;
while (i!=cursor_move1)
{
cursor1=s->top;
cursor2=s->top;
move_cursor(cursor1, i);
move_cursor(cursor2, cursor_move2);
if(strcmp(cursor1->s,cursor2->s)!=0)
{
check=0;
break;
}
else
{
i++;
cursor_move2++;
}
}
}
if(check==0)
printf("%d Neg", check);
else
printf("1Pos");
}
void display(TOP *top)
{
STACK *cursor;
cursor=top->top;
while(cursor->next==NULL)
{
printf("%s pos\n ", cursor->s);
cursor=cursor->next;
}
}
int main()
{
char input[1000];
TOP top;
top.num=0;
top.top=NULL;
fgets(input, 100, stdin);
input[strlen(input)-1]='\0';
create_stack(&top, input);
printf("%d \n ", top.num);
display(&top);
printf("---------------------------------------------------------\n");
compare(&top);
return 0;
}
最佳答案
您的代码中存在不同的问题。最大的一个解释是,如果您在开始循环之前只在堆栈中创建一个元素,而您显然需要为每个字分配一个元素,那么为什么您无法填充堆栈。此外,您还忘记将顶部元素的 next
值初始化为 NULL。顺便说一句,在 C 中你永远不应该强制使用 malloc。
create_stack 应该变成:
void create_stack(TOP *s, char str[1000])
{
char temp1[30];
int i=0, j=0;
STACK *temp;
temp=malloc(1*sizeof(STACK));
temp->next = NULL; // must be explicitely NULL for further use
while(1)
{
if(str[i]!=' ' && str[i]!='\0')
{
temp1[j]=str[i];
j++;
}
else
{
temp1[j]='\0';
strcpy(temp->s,temp1);
printf("%s\n", temp->s);
if(s->top==NULL)
{
s->top=temp;
s->num=1;
}
else
{
temp->next=s->top;
s->top=temp;
s->num++;
}
j=0;
temp=malloc(1*sizeof(STACK)); // time to allocate a new element
}
if(str[i]=='\0')
{
free(temp); // last allocated has not been used
break;
}
i++;
}
}
在显示中,你的循环测试是完全错误的,它应该是 while(cursor!=NULL)
修复此问题后,您应该使用调试器来了解比较是否未给出预期结果。无论如何,我的观点是,您应该分配一个指向 STACK 元素的指针数组,将堆栈内容提供给它一次,并使用该数组直接在数组元素之间进行比较(即按索引),而不是重复移动光标。
关于c - C 语言中的一堆单词(回文句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438530/