实施例: “这是一个例子”应该变成“例子就是这个” 应将一个字符存储为每个节点的信息。 在这样做之后,我能够逆转整个句子(即 - >“elpmaxe na si sihT”)。现在我该如何反转每个单词才能得到:“例如一个是这个”
#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);
}
答案 0 :(得分:0)
读取每个单词并将其作为char数组添加到节点。然后从头到尾阅读你的链表。你会得到相反的判决。
-------------------------------
+ *prev + "This" + *next +
-------------------------------
------------------------
+ *prev + "is" + *next +
------------------------
------------------------
+ *prev + "an" + *next +
------------------------
-----------------------------
+ *prev + "example" + *next +
-----------------------------
现在使用* prev。
从最后阅读答案 1 :(得分:0)
更好的方法是将一个单词存储为每个节点的信息。 像这样:
#define LEN 10
struct node{
struct node *ptr;
char info[LEN+1]; // the length of each word cannot be more than LEN
};
或
struct node{
struct node *ptr;
char *info;
};
然后你可以使用你的rev功能来实现你的目标。
如果您不想更改节点的结构,则应根据空白将句子分为单词。你可以先翻转每个单词,然后翻转整个句子。
像这样: “这是一个例子” - &gt; “sihT si na elpmaxe” - &gt; “例子是这个”