例子: “This is an example”应该变成“example an is This” 每个节点的信息应存储一个字符。 这样做之后,我可以反转整个句子(即->“elpmaxe na si sihT”)。现在我如何反转每个单词以获得:“example an is This”
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node {
struct node *ptr;
char info;
};
struct node *first,*ic;
struct node * insertn(int n,struct node * first)
{
struct node *temp,*cur;
temp=(struct node *)malloc(sizeof(struct node));
temp->info=n;
temp->ptr='\0';
if(first=='\0')
{
return temp;
}
else{
cur=first;
while(cur->ptr!='\0')
cur=cur->ptr;
cur->ptr=temp;
return first;
}
}
void disp( struct node *first)
{
printf("here");
struct node *cur;
cur=first;
while(cur!='\0')
{
printf("%c",cur->info);
cur=cur->ptr;
}
}
void rev(struct node * p)
{
if(p->ptr=='\0')
{
first =p;
return;
}
rev(p->ptr);
struct node *q=p->ptr;
q->ptr=p;
p->ptr='\0';
}
main()
{
char n;
int i=0;
first='\0';
ic='\0';
while(i<7)
{
i++;
printf("Enter element:");
scanf("%c",&n);
first=insertn(n,first);
}
printf("ELEMENTS OF LIST BEFORE REV:");
disp(first);
rev(first);
printf("\n\nELEMENTS OF LIST AFTER REV:");
disp(first);
}
最佳答案
读取每个单词并将其作为 char 数组添加到节点。然后从头到尾阅读你的链表。你会得到相反的句子。
-------------------------------
+ *prev + "This" + *next +
-------------------------------
------------------------
+ *prev + "is" + *next +
------------------------
------------------------
+ *prev + "an" + *next +
------------------------
-----------------------------
+ *prev + "example" + *next +
-----------------------------
现在使用 *prev 从头开始阅读。
关于c - 如何反转链表中句子的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17806316/