#include <iostream>
#include<stdlib.h>

#define MAXSIZE 10000
#define OK 0
#define ERROR 1
#define OVERFLOW 0

typedef int Status;

typedef struct
{
    char no[20];
    char name[50];
    double price;
}Book;

typedef struct
{
    Book* elem;
    int length;
}SqList;

Status InitList(SqList& L)
{
    L.elem = new Book[MAXSIZE];//申请分配空间
    if (!L.elem) exit(OVERFLOW);//分配失败就退出
    L.length = 0;//空表长度为0
    return OK;
}

Status GetElem(SqList L, int i, Book& e)
{
    if (i<1 || i>L.length)
        return ERROR;//取值,不合理返回error
    e = L.elem[i - 1];//
    return OK;
}

int LocateElem(SqList L, Book e)
{
    for (int i = 0; i < L.length; i++)//比较
        if (strcmp(L.elem[i].no, e.no) == 0)
            return i + 1;//查找成功,返回i+1
    return 0;//查找失败,返回0
}

Status ListInsert(SqList& L, int i, Book e)
{
    if ((i < 1) || (i > L.length + 1)) {
        return ERROR;//判断i是否合法
    }
    if (L.length == MAXSIZE) {
        return ERROR;//判断储存空间
    }
    for (int j = L.length - 1; j >= i - 1; j--) {
        L.elem[j + 1] = L.elem[j];//移位置
    }
    L.elem[i - 1] = e;
    ++L.length;
    return OK;
}

Status ListDelete(SqList& L, int i)
{
    if ((i < 1) || (i > L.length))
        return OK;
    for (int j = i; j <= L.length - 1; j++)
        L.elem[j - 1] = L.elem[j];
    --L.length;
    return OK;
}

Status ListModify(SqList& L, int i, Book newElem) {
    if (i < 1 || i > L.length) {
        return ERROR;
    }
    strcpy(L.elem[i - 1].no, newElem.no);
    strcpy(L.elem[i - 1].name, newElem.name);
    L.elem[i - 1].price = newElem.price;
    return OK;
}


void ListPrint(SqList L) {
    if (L.length == 0)
        return;
    for (int i = 0; i < L.length; i++)
        printf("idx: %d %s %s %f\n", (i + 1), L.elem[i].name, L.elem[i].no, L.elem[i].price);
}

int main()
{
    SqList list = { 0 };

    InitList(list);

    Book book;
    strcpy(book.no, "1234");
    strcpy(book.name, "现代心理学");
    book.price = 99999.9999;
    ListInsert(list, 1, book);

    strcpy(book.no, "12343");
    strcpy(book.name, "Early");
    book.price = 89;
    ListInsert(list, 2, book);

    strcpy(book.no, "1111");
    strcpy(book.name, "Star");
    book.price = 200;
    ListInsert(list, 3, book);

    Book newElem;
    strcpy(newElem.no, "1790");
    strcpy(newElem.name, "Better Life");
    newElem.price = 176.98;

    ListPrint(list);

    std::cout << std::endl;

    ListModify(list, 3, newElem);

    ListPrint(list);

    std::cout << std::endl;

    ListDelete(list, 2);

    ListPrint(list);

    return 0;
}
最后修改:2023 年 07 月 05 日
如果觉得我的文章对你有用,请随意赞赏