链表
介绍
当我们想储存一串数据时,可能会定义一个数组a,然后思考该数组的大小。且当我们想在其中插入数据时,需要进行麻烦的数据移位,更要防止数组溢出。
这个时候我们就可以用链表来代替数组,链表作为一种重要的数据结构,有着非常灵活的数据处理方式,可以进行动态的内存分配。链表,顾名思义,是由一个个节点组成的数据链条,我们可以对其进行自由的删除、添加。链表分为单向链表、双向链表、循环链表等。本文主要讨论单向链表。
函数
malloc函数
void *malloc(unsigned int size);
//size:分配内存的大小,一般可通过sizeof函数进行计算。
//返回:返回一个不指向任何数据类型的地址,需要在使用时进行强制转换,如(int *)。
free函数
void free(void *p);
//释放内存空间
程序实现
#include <stdio.h>
#include <stdlib.h>
#define EMPTY_LIST NULL
/* 创建空链表-头结点 */
struct list_node* list_init(int id);
/* 在表尾插入节点 */
void append_node(struct list_node *head);
/* 遍历链表元素 */
void display_list(struct list_node *head);
/* 删除链表*/
void DeletMemory(struct list_node *head);
/* 插入元素 */
void insert_node(struct list_node *node, int num);
struct list_node
{
int data;
struct list_node* next_node;
};
int main (void)
{
int i = 0;
int pos;
char isAppendNode= 'N';
char isInsertNode= 'N';
/* Start List */
/* Start List */
struct list_node *head_node = NULL;
head_node = list_ini