【C语言】编写一个程序,读入一行字符,且每个字符存入一个结点,按输入顺序建立一个链表的结点序列,然后按相反顺序输出并释放全部结点。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>

struct node
{
    char a;
    struct node *next;
};
int main()
{
        struct node *p,*q,*h,*t;
        int count=0,j;
        h = (struct node*)malloc(sizeof(struct node));
        p = (struct node*)malloc(sizeof(struct node));
        q = (struct node*)malloc(sizeof(struct node));
        h->next = p;
        char b[10];
        printf(“请输入一行字符:\n”);
        gets(b);
        for(int i=0;b[i]!=’\0′;i++)
        {

            p->a = b[i];
            p->next = q;//链接
            p = p->next;//p指向下一个
            q = (struct node*)malloc(sizeof(struct node));
            count++;
        }
        p->next = NULL;
        free(q);

        while(1)
        {
            j=1;//t指向第一个结点,所以从1开始计数
            t = h->next;
            while(j!=count)
            {
                j++;
                t = t->next;

            }
            count–;//逆序输出

            printf(“%c”,t->a);
            free(t);
            if (count ==0)
                break;
        }

        return 0;
}

    原文作者:Klay_thompson11
    原文地址: https://blog.csdn.net/Klay_thompson11/article/details/126374364
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞