小言_互联网的博客

C语言/数据结构·单链表

250人阅读  评论(0)

同样这个代码 是根据我对书上代码的理解写的
对书上一些没必要的步骤进行了删减

#include<stdio.h>
#include<stdlib.h>
struct link
{
    int data;
    struct link *next;
};
struct link *Append(struct link *head)
{
    struct link *p = NULL , *pr = head ;
     p = (struct link *)malloc(sizeof(struct link));
    if(p==NULL)
    {
        printf("error");
        exit(0);
    }
    if(head ==NULL)
    {
        head =p;
    }

    else
    {
        while(pr->next !=NULL)
        {
            pr = pr->next;
        }
        pr->next= p;
    }
    printf("输入该节点数据:");
    scanf("%d",&p->data);
    p->next=NULL;
    return head;
}
void DeleteMemory(struct link *head)
{
    struct link *p =head, *pr =NULL;
    while(p != NULL)
    {
        pr =p;
        p= p->next;
    }
    free(pr);
}
void DisplayNode(struct link *head)
{
    struct link *p=head;
    while(p!=NULL)
    {
        printf("%10d",p->data);
        p= p->next;
    }
}
void main()
{
    struct link *head=NULL;     //  读者可以试试 不将head 赋空值   嘿嘿
    int i=0;
    char c;
    printf("你想创建一个新单向链表吗?");
    scanf(" %c",&c);            //  注意 : 此处有空格  否则无法进行多次输入    
    while(c=='y' || c=='Y')     
    {
        head = Append(head);      
        DisplayNode(head);
        printf("还要创建元素吗?");
        scanf(" %c",&c);
        i++;                          // 书上的计数    为了提醒各位就不删了   
    }
    DisplayNode(head);     
    DeleteMemory(head);   //因为malloc函数是进行动态存储空间分配  所以完了要释放
}


转载:https://blog.csdn.net/weixin_44527253/article/details/102252431
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场