C语言实现顺序表基本操作

本文介绍如何使用C语言实现顺序表的以下基本操作:

  • 初始化顺序表
  • 创建顺序表
  • 判断顺序表是否为空
  • 获取顺序表长度
  • 清空顺序表
  • 销毁顺序表

代码示例

#include<stdio.h>
#include<stdlib.h>

#define MAXSIZE 100
#define ERROR 0
#define OK 1

typedef int Status;
typedef int ElemType;

// 定义顺序表结构 
typedef struct
{
    ElemType *elem;
    int length;    
    int listsize;
}SqList ;

Status InitList(SqList &L); // 初始化函数声明
Status CreateList(SqList &L,int a[],int n); // 构造函数声明
void DispList(SqList L) ; // 显示顺序表内容

// 判断顺序表是否为空
Status IsEmpty(SqList L) 
{
    if(L.length!=0)
        return 0;
    else
        return 1;
}

// 获取顺序表长度
Status ListLength(SqList L) 
{
    return (L.length);
}

// 清空顺序表
void ClearList(SqList &L) 
{
    L.length=0;
}    

// 销毁顺序表
void DestoryList(SqList &L) 
{
    if(L.elem) 
        free(L.elem);
}

int main()
{
    int a[]={16,6,2,9,11,8,1};
    SqList L;
    
    InitList(L); // 初始化顺序表
    CreateList(L,a,sizeof(a)/sizeof(a[0])); // 构造顺序表
    
    if(IsEmpty(L)==1)
        printf('空表\n');
    else
    {
        printf('非空表\n');
        printf('表长为:%d\n',ListLength(L));
    }
    
    ClearList(L);
    printf('清空后表长为:%d\n',ListLength(L));
    
    DestoryList(L);
    if(!L.elem)
        printf('销毁表后:该表已经销毁\n');
    
    return 0;    
}

// 初始化顺序表
Status InitList(SqList &L) 
{
    L.elem = (ElemType *)malloc(MAXSIZE * sizeof(ElemType));
    if (!L.elem)
    {
        return ERROR;
    }
    L.length = 0;
    L.listsize = MAXSIZE;
    return OK;
}

// 构造与数组a相同内容的顺序表
Status CreateList(SqList &L, int a[], int n) 
{
    if (n > L.listsize)
    {
        return ERROR;
    }
    for (int i = 0; i < n; i++)
    {
        L.elem[i] = a[i];
    }
    L.length = n;
    return OK;
}

// 显示顺序表内容
void DispList(SqList L) 
{
    for (int i = 0; i < L.length; i++)
    {
        printf('%d ', L.elem[i]);
    }
    printf('\n');
}

代码解释

  1. SqList结构体定义了顺序表的结构,包含三个成员:

    • elem: 指向存储空间基地址的指针
    • length: 顺序表的当前长度
    • listsize: 顺序表最大可容纳元素个数
  2. InitList函数初始化顺序表,为elem指针分配存储空间,并将length设置为0,listsize设置为MAXSIZE

  3. CreateList函数根据给定的数组a创建顺序表,并将数组元素复制到顺序表中。

  4. IsEmpty函数判断顺序表是否为空,如果length为0则为空,否则非空。

  5. ListLength函数返回顺序表的当前长度length

  6. ClearList函数清空顺序表,将length设置为0,但不释放存储空间。

  7. DestoryList函数销毁顺序表,释放elem指针指向的存储空间。

  8. main函数中演示了如何使用这些函数进行顺序表的基本操作。

总结

本文介绍了使用C语言实现顺序表基本操作的方法,并提供了详细的代码示例和解释。理解顺序表的实现对于学习数据结构和算法至关重要,希望本文能够帮助读者更好地掌握顺序表的基本操作。

C语言实现顺序表基本操作(初始化、创建、判空、长度、清空、销毁)

原文地址: https://www.cveoy.top/t/topic/4Uc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录