C语言实现不带头结点的单向链表(尾插法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38022615/article/details/82025495

前篇博客已经讲了不带头结点的头插法,此篇将讲解的是不带头结点的尾插法。
代码如下:

/*********************************************************************************
 *      Copyright:  (C) 2018 Dinghuanhuan<[email protected]>
 *                  All rights reserved.
 *
 *       Filename:  tail_nohead_link.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(08/24/2018)
 *         Author:  Dinghuanhuan <[email protected]>
 *      ChangeLog:  1, Release initial version on "08/24/2018 05:16:06 PM"
 *                 
 ********************************************************************************/

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

typedef struct node_s
{
    int             data;//链表的数字域
    struct node_s   *next;//链表的next域
}node_t,*pnode_t;


void travel_list(pnode_t node);
void destroy_list(pnode_t node);

int main(int argc, char **argv)
{
    pnode_t    node  = NULL;
    pnode_t    head  = NULL;
    pnode_t    tail  = NULL;
    int        i;
    for(i=0; i<5;i++)
    {
      node = malloc(sizeof(pnode_t));
      if(node == NULL)
      {
          printf("malloc failure\n");
          return -1;

      }
      node->data = i+1;
      node->next = NULL;

      if(head == NULL)
      {
          head = node;
          tail = node;
          printf("add node:%d\n",head->data);
      }
      else
      {
          tail ->next = node;
          tail = node;
          printf("add node:%d\n",tail->data);

      }
    }
    travel_list(head);
    destroy_list(head);
    return 0;
}

void travel_list(pnode_t head)
{
    pnode_t     node = head;
    while(node != NULL)
    {
        printf("tarvel_node[%d]\n",node->data);
        node = node ->next;
    }
}

void destroy_list(pnode_t head)
{
    pnode_t     node = head;
    while(node != NULL)
    {
        head = head ->next;
        printf("destroy node[%d]\n",node->data);
        free(node);
        node = node->next;

    }
}

代码执行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/m0_38022615/article/details/82025495