C 语言动态顺序表

test.h

cpp 复制代码
#ifndef _TEST_H
#define _TEST_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef int data_type;

// 定义顺序表结构体
typedef struct List{
    data_type *data; // 顺序表数据
    int size; // 顺序表当前长度
    int count; // 顺序表容量
}list;

typedef enum{
    OK,
    LIST_EMPTY,
    LIST_FULL,
    INDEX_ERROR,
   
}RETURNVALUE;


list *create_list(void);

int list_insert(list *plist, int index, data_type data);

int list_show(list *plist);

#endif

main.c

cpp 复制代码
#include "../include/test.h"

int main()
{
    int retval = 0;

    list *plist = create_list();

    retval = list_insert(plist, 0, 1);
    retval = list_insert(plist, 1, 2);
    retval = list_insert(plist, 2, 3);
    retval = list_insert(plist, 1, 4);

    
    retval = list_show(plist);

    return 0;
}

crud.c

cpp 复制代码
#include "../include/test.h"

// 创建动态顺序表
list *create_list(void)
{
    int list_size = 0; // 初始化顺序表大小
    list *plist = (list *)malloc(sizeof(list)); // 申请内存空间
    if(plist == NULL){
        perror("plist malloc error!");
        return NULL;
    }

    memset(plist, 0, sizeof(list)); // 清零

    // 手动输入顺序表大小
    printf("请输入顺序表大小:");
    scanf("%d", &list_size);

    // 申请内存空间
    plist->data = (data_type *)malloc(sizeof(data_type) * list_size);

    // 初始化顺序表的大小
    plist->size = list_size;
    return plist; // 返回顺序表指针
}

int list_insert(list *plist, int index, data_type data)
{
    // 入参检测
    if(plist == NULL){
        return LIST_EMPTY;
    }
    
    // 检测顺序表是否已满
    if(plist->count == plist->size){
        return LIST_FULL;
    }

    // 检测插入位置是否合法
    if(index < -1 || index > plist->count){
        return INDEX_ERROR;
    }

    // 插入操作:尾插
    if(index == -1){
        plist->data[plist->count] = data;
        plist->count++;
        return OK;
    }

    // 移动元素,实际上在用户按规律顺序插入元素的时候,不会调用此循环,而是直接
    // 执行 plist->data[index] = data; 的操作
    for(int i = plist->count; i > index; i--){
        printf("for(int i = plist->count; i > index; i--){\n");
        plist->data[i] = plist->data[i - 1];
    }

    // 插入元素
    plist->data[index] = data;

    // 顺序表元素个数加一
    plist->count++;

    return OK;
}

int list_show(list *plist)
{
    if(plist == NULL || plist->count == 0){
        return LIST_EMPTY;
    }
    
    // 遍历顺序表
    for(int i = 0; i < plist->count; i++){
        printf("%d\t\n", plist->data[i]);
    }
    putchar(10);

    return OK;
}
相关推荐
巭犇17 分钟前
c语言中define使用方法
c语言·开发语言
奇点 ♡1 小时前
【线程】线程的控制
linux·运维·c语言·开发语言·c++·visual studio code
铁匠匠匠4 小时前
【C总集篇】第八章 数组和指针
c语言·开发语言·数据结构·经验分享·笔记·学习·算法
王哈哈嘻嘻噜噜4 小时前
c语言中“函数指针”
java·c语言·数据结构
别耗尽5 小时前
错题集锦之C语言
c语言
六点半8885 小时前
【C/C++】速通涉及string类的经典编程题
c语言·开发语言·c++·算法
Jack黄从零学c++6 小时前
自制网络连接工具(支持tcpudp,客户端服务端)
linux·c语言·开发语言·网络协议·tcp/ip·udp·信息与通信
day3ZY6 小时前
清理C盘缓存,电脑缓存清理怎么一键删除,操作简单的教程
c语言·开发语言·缓存
疑惑的杰瑞7 小时前
[数据结构]算法复杂度详解
c语言·数据结构·算法
hong1616889 小时前
VSCode中配置C/C++环境
c语言·c++·vscode