c - 如何反转链表中句子的单词?

标签 c linked-list word reverse

例子: “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/

相关文章:

两个指针变量可以指向同一个内存地址吗?

英语单词复数形式的Java API

c++ - 使用 regsvr32 时在 Windows dll 中找不到入口点

c++ - 非阻塞套接字上的挂起程序

Java - 通用链表值比较在值大于 127 时失败

c++ - ifstream - 移动到下一个单词

python - 如何使这个随机文本生成器在 Python 中更高效?

c - Eclipse 包含其他项目的头文件

c++ - c/c++关于指针的问题(双指针)

c - 在 C 中将节点添加到链表的末尾