C语言实现链表的各种功能
链表的定义
链表是一种数据结构,它是由一系列节点组成的线性结构。每个节点包含两个部分:数据和指针。数据部分存储着实际的数据,指针部分指向下一个节点。
链表的特点是:
- 每个节点都可以自由地插入或删除。
- 链表的第一个节点称为头节点,最后一个节点称为尾节点。
- 链表中节点的数量可以动态变化。
链表的实现
链表的实现可以分为两步:
- 定义链表节点的结构。
- 实现链表的操作函数。
定义链表节点的结构
文件名:link_list.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef int ElemType;
typedef struct linkList{
ElemType data;
struct linkList* next;
}LNode;
//初始化链表
bool initList(LNode** head);
//链表是否为空
bool isEmpty(LNode* head);
//链表长度
int length(LNode* head);
//链表头部插入元素
bool insert(LNode* head, ElemType data);
//链表尾部插入元素
bool append(LNode* head, ElemType data);
//插入链表指定位置
bool insertAt(LNode* head, ElemType data, int pos);
//链表删除元素头删
bool delete(LNode* head);
//链表删除指定位置元素
bool deleteAt(LNode* head, int pos);
//删除链表元素尾删
bool deleteTail(LNode* head);
//链表中查找指定位置元素
LNode* searchAt(LNode* head, int pos);
//修改链表指定位置元素
bool modify(LNode* head, ElemType data, int pos);
//清空链表
bool clearList(LNode* head);
//销毁链表
bool destroyList(LNode** head);
//打印链表
bool printList(LNode* head);
实现链表的操作函数
文件名:link_list.c
#include "link_list.h"
#define DEBUG_PRINT 1
//初始化链表
bool initList(LNode** head){
if(NULL==head){
#if DEBUG_PRINT
printf("初始化链表的入参为空\n");
#endif
return false;
}
//初始化 calloc()申请的空间自动初始化为0
(*head)=(LNode*)calloc(1, sizeof(LNode));
(*head)->next=NULL;
(*head)->data=0;//头节点中数据用来保存链表中的元素个数
return true;
}
//链表是否为空
bool isEmpty(LNode* head){
if(NULL==head){
#if DEBUG_PRINT
printf("isEmpty()的入参为空\n");
#endif
return false;
}
if(head->next==NULL){
return true;
}
return false;
}
//链表长度
int length(LNode* head){
if(NULL==head){
#if DEBUG_PRINT
printf("length()的入参为空\n");
#endif
return false;
}
return head->data;
}
//链表头部插入元素
bool insert(LNode* head, ElemType data){
//入参判断
if(NULL==head){
#if DEBUG_PRINT
printf("insert()的入参为空\n");
#endif
return false;
}
//为新节点申请空间
LNode * newNode=(LNode*)calloc(1, sizeof(LNode));
newNode->data=data;
newNode->next=head->next;
head->next=newNode;
head->data++;
}
//链表尾部插入元素
bool append(LNode* head, ElemType data){
//入参判断
if(NULL==h

最低0.47元/天 解锁文章
5042

被折叠的 条评论
为什么被折叠?



