データ構造とアルゴリズム - 線形テーブル - 線形ストレージ構造

データ構造における線形テーブルの最初の物理構造 - シーケンシャル ストレージ構造。その C++ 実装コードは次のとおりです。

#ifndef SHUNXUBIAO_H
#define SHUNXUBIAO_H
#include <iostream>
using namespace std;
#define MAX_SIZE 100
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef int Status;
typedef struct {
    ElemType *elem;
    int length;
}SqList;
//顺序表的初始化
Status InitList(SqList& L) {
    L.elem = new ElemType[MAX_SIZE];
    if (!L.elem)
    {
        return ERROR;
    }
    L.length = 0;
    return OK;
}
//顺序表的销毁
Status DestroyList(SqList& L)
{
    if (L.elem)
    {
        delete L.elem;
        return TRUE;
    }
    return FALSE;
}
//线性表的清空
void ClearList(SqList& L)
{
    L.length = 0;
}
//判断线性表是否为空
Status IsEmpty(SqList& L)
{
    if (L.length > 0) 
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}
//返回线性表L的元素个数
int ListLength(SqList& L)
{
    return L.length;
}
//线性表的取值
Status GetElem(const SqList& L, const int i, ElemType& e)
{
    if (L.length==0 || i<1 || i>L.length)
    {
        return FALSE;
    }
    e = L.elem[i - 1];
    return true;
}
//线性表的插入
Status ListInsert(SqList& L, const ElemType& e, const int& i)
{
    if (L.length == MAX_SIZE)
    {
        cout << "内存已满,无法插入" << endl;
        return FALSE;
    }
    if (i<=0 || i>L.length+1)
    {
        cout << "插入的位置不对" << endl;
        return FALSE;
    }
    if (i<=L.length)
    {
        for (int p = L.length - 1; p >= i-1; --p)
        {
            L.elem[p + 1] = L.elem[p];
        }
    }
    L.elem[i-1] = e;
    L.length += 1;
    return true;
}
//线性表的删除
Status ListDelete(SqList& L, const int& i, ElemType &e)
{
    if (L.length == 0)
    {
        cout << "线性表为空,无法删除" << endl;
        return ERROR;
    }
    if (i<1 || i>L.length)
    {
        cout << "删除位置不正确" << endl;
        return ERROR;
    }
    e = L.elem[i - 1];
    if (i < L.length)
    {
        for (int k = i; k < L.length; k++)
        {
            L.elem[k - 1] = L.elem[k];
        }
    }
    L.length--;
    return OK;
}
//线性表的查找
int LocateElem(SqList& L, ElemType& e)
{
    for (int i = 0; i < L.length; i++)
    {
        if (L.elem[i] == e)
        {
            return i + 1;
        }
    }
    //如果没有相等的元素,则返回0
    return 0;
}
#endif // !SHUNXUBIAO_H

おすすめ

転載: blog.csdn.net/hu853712064/article/details/123615069