前言
C语言初学阶段最主要的两个数据结构使用,一个是数组,一个是链表。
链表准确的地说是一种数据结构;
特点:将多个数据元素通过指针串联起来,不需要这些数据元素内存地址连续;链表可以保存多个数据元素;链表中的每个元素称为数据结点。
与数组比较,数组地址空间必须连续,数组大小固定,无法动态增加或减少数据元素。
链表空间大小动态分配,根据需要可以增加或减少数据元素个数,缺点是增加了指针成员,占用一部分空间,链表访问任意结点无法使用下标访问,必须从头到尾查找。
注1:这里是简单链表实现,链表高级知识会在数据结构等专业课上学习。
注2:链表有单向链表、双向链表、循环链表、带头指针和尾指针的链表等。
链表实现要点
1.引入相关头文件,链表内存空间是动态申请和分配的,因此需要使用动态内存管理函数。
2.定义数据结点结构类型:data成员是保存数据,next是指向下一个结点的指针,通过该指针可以访问到下一个结点的数据。
struct node{
int data;
struct node* next;
};
3.定义链表的头结点head:头结点用来指向链表的第一个结点,当链表为空时,头结点的next是NULL空指针,data可以用来保存链表元素个数。
struct node *head = (struct node*)malloc(sizeof(struct node));
head->data = 0;
head->next = NULL;
注:头结点实现链表,后续实现相关操作方便,链表另一种方式是使用头指针实现链表,定义一个指针指向第一个元素,当链表为空时,头指针是NULL空指针。
4.动态创建链表数据结点:对数据成员初始化。
struct node *p = (struct node*)malloc(sizeof(struct node));
p->data = 0;
p->next = NULL;
5.释放数据结点:当删除链表元素时,需要释放结点。
带头结点的链表简单实现代码模板
功能:输入数据元素个数和对应的数据元素,生成带头结点的链表,并且打印出来。
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点结构类型
struct node{
int data;
struct node *next;
};
// 定义创建结点元素函数
struct node *createNode(int data){
struct node *p = (struct node *)malloc(sizeof(struct node));
if (p != NULL){
p->data = data;
p->next = NULL;
}
return p;
}
// 新增的结点元素插入链表的末尾,保持输入数据的初始顺序
// 插入成功,返回插入的结点指针,失败返回NULL
struct node *insertNode(struct node *head, int data){
if (head != NULL){
struct node *node = createNode(data);
if (node != NULL){
struct node *p = head;
// 循环找到链表最后的结点
while (p->next != NULL)
p = p->next;
p->next = node;
head->data++;
return node;
}
}
return NULL;
}
// 创建带头结点的链表
struct node *createList(){
// 头结点的data保存链表长度,初始为0
return createNode(0);
}
// 释放所有链表内存空间
void freeList(struct node *head){
struct node *p = head;
while (p != NULL){
head = p->next;
free(p);
p = head;
}
}
// 打印出链表所有结点值
void printList(struct node *head){
struct node *p = head->next;
while (p != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main(void){
// 创建链表保存数据
struct node *list = createList();
int num;
printf("请输入数据个数:");
scanf("%d", &num);
printf("请输入%d个整数,以回车结束:", num);
int i = 0, t = 0;
for (i = 0; i < num; i++){
scanf("%d", &t);
insertNode(list, t);
}
printf("当前链表元素有:");
printList(list);
freeList(list);
return 0;
}
运行结果:
请输入数据个数:6
请输入6个整数,以回车结束:1 2 3 4 5 6
当前链表元素有:1 2 3 4 5 6
---------- End ----------