数据结构之线性表算法的构建与应用

//数据结构值顺序线性表的实现与应用

//c++代码进行实现

//sqlist.h代码                     //线性表的初始化

#define MAXSIZE 20
//typedef int ElemType;
typedef struct{
    int date[MAXSIZE];
    int length;
}sqList;

//getlem.h代码


#define OK 1
#define ERROR 0
#define FALSE 0
#define TRUE 1
//typedef int Status;
int Getlem(sqList L, int i, int *e)              // 获取第i个位置上的数据返回给变量e
{
    if (L.length == 0 || i<1 || i>L.length)
        return ERROR;
    *e = L.date[i - 1];
    return OK;
}

//listinsert.h代码

int ListInsert(sqList *L, int i, int e)     //插入算法
{
    int k;
    if (L->length == MAXSIZE)
        return ERROR;
    if (i<1||i>L->length+1)
        return ERROR;
    if (i <= L->length)
    {
        for (k = L->length; k > i - 1; k--)
            L->date[k] = L->date[k-1];
    }
    L->date[i-1] = e;
    L->length++;
    return OK;
}

//listdelete.h代码

int ListDelete(sqList *L, int i, int *e)      // 删除算法
{
    int k;
    if (i > L->length || i < 1)
        return ERROR;
    if (L->length == 0)
        return ERROR;
    *e = L->date[i - 1];
    if (i < L->length)
    {
        for (k =i; k < L->length; k++)
            L->date[k - 1] = L->date[k];
    }
    L->length--;
    return OK;
}

//主程序

#include<stdlib.h>
#include<sqList.h>
#include<Getlem.h>
#include<ListDelete.h>
#include<ListInsert.h>
#include<iostream>
#include<ctime>
const int Length = 20;
void main()
{
    using std::cout;
    using std::cin;
    using std::endl;
    sqList L;
    L.length = Length;
    int i = 0;
    int ch;
    int e;
    //线性表的赋值

    srand(time(NULL));
    for (; i < L.length; i++)
    {
        L.date[i] = rand() % 100 + 1;
    }

    ////线性表的打印输出

    cout << "sqList:";
    for ( i = 0; i < Length; i++)
    {
        cout << L.date[i] <<" ";

    }
    cout << endl;

    //获取第8位置上的元素的值

    ch=Getlem(L, 8, &e);
    cout << "getlem ch:" << ch<<endl;
    cout << "getlem e:" << e << endl;

    //删除第8 个元素上面的值

    ch=ListDelete(&L, 8, &e);
    cout << "listdelete ch:" << ch << endl;
    cout << "listdelete e:" << e << endl;
    for (i = 0; i < L.length; i++)
    {
        cout << L.date[i] << " ";

    }

    //在第八个元素位置插入数值233

    ch = ListInsert(&L, 8, 233);
    cout << "listinsert ch:" << ch << endl;
    cout << "listinsert e:" << e << endl;
    for (i = 0; i < L.length; i++)
    {
        cout << L.date[i] << " ";

    }
    system("pause");
}

猜你喜欢

转载自blog.csdn.net/zj490044512/article/details/81254426
今日推荐