我想把“你好世界”变成“你好世界”。
但代码并没有按照我希望的方式正常工作。
请参见下面的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct llnode
{
char *info;
struct llnode *next;
};
typedef struct llnode NODE;
int main()
{
char msg[50],word[10],*str;
int i=0,length=0,j=0;
NODE *ptr,*front=NULL,*temp,*last=NULL;
//printf("Enter the sentence: ");
str= "Hello World"; //fgets(msg,sizeof(msg),stdin);
while(str[i]!='\0')
{
if((str[i]==' ')||(str[i]=='\n'))
{
word[j]='\0';
j=0;
ptr=(NODE *)malloc(sizeof(NODE));
ptr->info=word;
ptr->next=NULL;
if(front==NULL)
{
front=ptr; // only change the value of front here;
}
else
{
temp=front;
while((temp->next)!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
printf("\n##%s\n",front->info); // prints thewords and not
//the first word
}
else
{
word[j]=str[i];
j++;
}
i++;
}
temp=front;
while(temp)
{
length++;
printf("%s ",temp->info);
temp=temp->next;
}
printf("\nLength of Linked List(or, number of words): %d\n",length);
i=0;
printf("\n************************\n");
while(i<length)
{
temp=front;
while(temp->next!=last)
{
temp=temp->next;
}
last=temp;
printf("%s ",temp->info);
i++;
}
return 0;
}
谢谢
最佳答案
代码有很多问题:
您使用一个单词数组来读取所有单词。所以,当你读到“Hello”时,你读入单词数组,打印“Hello”并将指向单词数组的指针存储为front->info。然后,用World覆盖单词数组。另外,请注意,您永远不要添加一个带有“Word”的节点,因为一旦遇到“0”,就退出循环。所以,链接列表只包含一个节点。但是,存在一个问题,因为在第一个节点中存储了指向单词数组的指针,并且由于Word数组已经被“Word”覆盖了,当您退出循环时,列表中只有一个节点,这个节点的信息是Word数组,它包含了“Word”,而不是“hello”。所以,我想这解释了输出?
关于c - 将字符串“Hello World”反转为“World Hello”,这是怎么回事?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9123762/