C语言实现带头结点的单向链表(尾插法)
程序员文章站
2022-05-11 22:36:52
...
此篇博文要实现的是用尾插法实现带头结点的单向链表的创建,遍历和摧毁。
代码如下:
*********************************************************************************
* Copyright: (C) 2018 Dinghuanhuan<736787419@qq.com>
* All rights reserved.
*
* Filename: tail_head_link.c
* Description: This file
*
* Version: 1.0.0(08/24/2018)
* Author: Dinghuanhuan <736787419@qq.com>
* 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;
head = malloc(sizeof(pnode_t));
head ->data = -1;
head ->next = NULL;
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->next == NULL)
{
head->next = node;
tail = node;
printf("add node:%d\n",tail->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;
}
}
代码执行结果如下:
上一篇: 自定义主题
下一篇: PHP扩展编写点滴 技巧收集_PHP