头插法创建单链表

1.对单链表的解释
链表与顺序表不同,它是一种动态管理的存储结构,链表中的每个结点占用的存储空间不是预先分配的,而是运行时系统根据需求生成的,因此建立单列表要从空表开始,每读入一个数据元素则申请一个结点,然后插入在链表中。建立链表的过程就是一个不断插入结点的过程。插入结点的位置可以始终在链表的表头结点之后,也可以不断插在链表的尾部。
2.程序展示

#include<stdio.h>
typedef struct node 
{
    int date;
    struct node *next;
}Node;
Node *creatList()//头插法创建链表
{
    //创建空表
    Node *head = (Node*)malloc(sizeof(Node));
    head->next = NULL;
    //给定一个指针cur,并置空;
    Node *cur = NULL;

    int date;
    printf("请输入结点数据:");
    scanf_s("%d", &date);

    while (date)
    {
        //创建一个新结点,即将要插入的结点
        cur = (Node*)malloc(sizeof(Node));
        cur->date = date;
        //链表插入的关键
        cur->next = head->next;//让新来的结点指向目标结点的下一个结点
        head->next = cur;

        scanf_s("%d", &date);
    }
    return head;
}
void traverseList(Node *head)//遍历输出链表数据元素
{
    head = head->next;
    while (head)
    {
        printf("%d\n", head->date);
        head = head->next;
    }
}
int main()
{ 
    Node *head = creatList();
    traverseList(head);
    return 0;
}

这里写图片描述
3.对逆序输出的解释
因为是在链表的头结点之后插入结点,因为建立的单链表和线性表的逻辑顺序是相反的,因此为了保证逻辑顺序和存储顺序的一致性,可以逆序输出数据元素。
二个结点

猜你喜欢

转载自blog.csdn.net/weixin_40995778/article/details/79977426
今日推荐