其他分享
首页 > 其他分享> > 带头结点的尾插法单链表——包括插入以及遍历

带头结点的尾插法单链表——包括插入以及遍历

作者:互联网

为了准备笔试面试,重新复习了单链表系列的数据结构

/*********************************************************************************
 *      Copyright:  (C) 2021 li liangshi<1007146932@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  have_head.c
 *    Description:  This file is 带头结点的尾插法单链表 
 *                 
 *        Version:  1.0.0(2021年09月07日)
 *         Author:  li liangshi <1007146932@qq.com>
 *      ChangeLog:  1, Release initial version on "2021年09月07日 09时13分15秒"
 *                 
 ********************************************************************************/
#include <stdlib.h>
#include <stdio.h>

/* 结点定义 */
typedef struct node_s
{
    int           value;
    struct node_s  *next;
}Node;

/* 声明头结点 */
Node  *head;

/* 初始化头结点 */
void Init_head(Node **head)
{
    *head =(Node *)malloc(sizeof(Node));
    (*head)->next = NULL;
}

/* 尾插法插入结点 */
void Inser_list(Node **head)
{
    int     num;
    int     i;
    int     data;
    Node    *node, *r = *head;
    
    printf("新建的单链表你想要插入多少个结点:");
    scanf("%d", &num);
    
    for(i=1; i<=num; i++)
    {
        printf("插入的第%d个结点:", i);
        scanf("%d", &data);

        node = (Node *)malloc(sizeof(Node));
        node->value = data;
        r->next = node;
        r = node;
    }
    printf("长度为%d的单链表已经建好!", num);
}

/* 遍历带头结点的单链表 */
void Ergodic_list(Node *head)
{
    Node        *node;
    printf("遍历单链表:");
    while(head->next != NULL)
    {
        node = head->next;
        printf("%d ", node->value);
        head = node;
    }
    printf("遍历完成!\n");
}


int main (int argc, char **argv)
{
    Init_head(&head);
    Inser_list(&head);
    Ergodic_list(head);
    return 0;
} 


标签:Node,插法,结点,遍历,node,int,head,单链
来源: https://blog.csdn.net/weixin_45506125/article/details/120152659