首页 > 试题广场 >

编写一个程序,读入一行字符,且每个字符存入一个节点,按输入顺

[问答题]
编写一个程序,读入一行字符,且每个字符存入一个节点,按输入顺序建立一个链表的节点序列,然后再按相反顺序输出并释放全部节点。

推荐
采用getchar()函数接受用户输入的字符,以尾插法建立一个带头节点的链表,然后从前向后输出节点的date域值并释放其全部节点。程序如下:
#include <stdio.h>
#include <malloc.h>
#define GetNode(type)  ((type * )malloc(sizeof(type)))
typedef struct node
{    char date;
     struct node * next;
}     NodeType;
NodeType * Create()                  /*根据输入建立带头节点的单链表* /
{
    char c;
    NodeType * head,* p, * r;
    head=GetNode(NodeType);            /*建立头节点*/
    r=head;                        /*r始终指向尾节点*/
    printf("输入一行字符:");
    while ((c=getchar())!='\n')
    {    p=GetNode(NodeType);        /*建立一个节点*/
       p->date=c;
       r->next=p;
       r=p;                       /*r始终指向尾节点*/
    }
    r->next=NULL;
    return(head);
}
void Output(NodeType * head)        /*输出并释放单链表*/
{
    NodeType * p=head, * q=p->next;
    printf("执行结果:");
    while (q!=NULL)
    {    printf("%c",q->date);
       free(p);
       p=q;
       q=p->next;
    }
    free(p);
    printf("\n");
}
void main()
{
    NodeType * h;
    h=Create();
    Output(h);
}

发表于 2018-04-16 21:18:19 回复(1)