顺序线性表的基本操作

  这个代码可以对顺序线性表进行查找、删除、插入、创建等基本操作。

#include<stdio.h>

struct node{
    int *List;
    int lenth;
};

typedef node *LIST, Lnode;

void PrintList(LIST L);//打印线性表
void CreatList(LIST &L, int n);//创建线性表
int GetElem(LIST L, int i);//查找给定位置的元素
int FindElem(LIST L, int e);//查找给定元素
void ListInsert(LIST L, int e, int j);//插入
void ListDelete(LIST L, int j);//删除给定位置的数

int main()
{
    int n, k;
    LIST SqList;
    CreatList(SqList, 6);
    if(k != -1) printf("%d\n\n", GetElem(SqList, 2));
    if(k != -1) printf("%d\n\n", FindElem(SqList, 3));
    ListDelete(SqList, 4);
    ListInsert(SqList, 99, 2);
    return 0;
}

void PrintList(LIST L)
{
    for(int i = 0; i < L->lenth; i++)
        printf("%d ", L->List[i]);
    printf("\n\n");
}

void CreatList(LIST &L, int n)
{
    int i;
    L->List = new int[n];
    L->lenth = 0;
    for(i = 0; i < n; i++)
        L->List[i] = i+1;
    L->lenth = i;
    PrintList(L);
}

int GetElem(LIST L, int i)
{
    if(i < 0 || i >= L->lenth){
        printf("输入错误!!\n");
        return -1;
    }
    return L->List[i];
}

int FindElem(LIST L, int e)
{
    for(int i = 0; i < L->lenth; i++)
        if(L->List[i] == e)
            return i;
    printf("未找到!!\n");
    return -1;
}

void ListInsert(LIST L, int e, int j)
{
    for(int i = L->lenth-1; i >= j; i--)
        L->List[i+1] = L->List[i];
    L->List[j] = e;
    L->lenth++;
    PrintList(L);
}

void ListDelete(LIST L, int j)//删除给定位置的数
{
    for(int i = j; i < L->lenth-1; i++)
        L->List[i] = L->List[i+1];
    L->lenth--;
    PrintList(L);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值