字符逆转

从键盘读入一个字符串,把它存入一个链表(每个结点存储1个字符),并按相反的次序将字符串输出到显示屏。

     有两种方来实现,一是建立倒序的链表,二是建立双向的链表。

     建立倒序的链表与建立正常的链表是相反的,这个过程可以理解为插入一个节点并且插入到头结点,而正常的是插到尾部,正好这个过程是相反的。有了这个思路建立倒序的链表就变得简单了。存入链表,然后按相反的次序的将字符串输出这个过程是和入栈出栈的过程是一样的,先进后出,后进先出。

    另一种方法是建立双向链表,这个是比较好理解的,但是这个过程会比较繁琐,相较于第一种方法就复杂了,每插入一个节点,都要把链表遍历一遍,再把插入到的尾部,打印时也要先遍历到尾部,才开始逆序输出字符串。

    代码如下:

 #include <stdio.h>

 #include <stdlib.h>


struct str{
    char s;
    struct str *ahead;
    struct str *next;
};


struct str1{
    char s;
    struct str1 *next;
};


struct str* add(struct str* head,char c);   //建立双向链表
struct str1* add1(struct str1* head,char c);  //建立倒序的链表


void print(struct str* head);
void print1(struct str1 *head);


int main()
{
    char c;
    struct str *head;
    struct str1 *head1;
    head=NULL;
    head1=NULL;
    while((c=getchar())!='\n')
    {
        head=add(head,c);
        head1=add1(head1,c);
    }
    print(head);
    print1(head1);
    return 0;
}


struct str* add(struct str* head,char c)
{
    struct str *p,*p1;
    if(head==NULL)
    {
        head=(struct str *)malloc(sizeof(struct str));
        head->ahead=NULL;
        head->next=NULL;
        head->s=c;
    }
    else
    {
        p=head;
        while(p->next!=NULL)
            p=p->next;
        p1=(struct str *)malloc(sizeof(struct str));
        p1->ahead=p;
        p1->next=NULL;
        p1->s=c;
        p->next=p1;
    }
    return head;
};


struct str1* add1(struct str1*head,char c)
{
    struct str1 *p1;
    if(head==NULL)
    {
         head=(struct str1 *)malloc(sizeof(struct str1));
         head->s=c;
         head->next=NULL;
    }
    else
    {
         p1=(struct str1*)malloc(sizeof(struct str1));
         p1->s=c;
         p1->next=head;
         head=p1;
    }
    return head;
}


void print(struct str* head)
{
    while(head->next!=NULL)
        head=head->next;
    while(head!=NULL)
    {
        printf("%c",head->s);
        head=head->ahead;
    }
    printf("\n\n\n");
}


void print1(struct str1 *head)
{
    while(head!=NULL)
    {
        printf("%c",head->s);
        head=head->next;
    }
    printf("\n\n\n");
}

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值