C语言 实现链表的各种功能

C语言实现链表的各种功能

链表的定义

链表是一种数据结构,它是由一系列节点组成的线性结构。每个节点包含两个部分:数据和指针。数据部分存储着实际的数据,指针部分指向下一个节点。

链表的特点是:

  • 每个节点都可以自由地插入或删除。
  • 链表的第一个节点称为头节点,最后一个节点称为尾节点。
  • 链表中节点的数量可以动态变化。

链表的实现

链表的实现可以分为两步:

  1. 定义链表节点的结构。
  2. 实现链表的操作函数。

定义链表节点的结构

文件名: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可能只会写BUG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值