数据结构——线性表

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define LISTSIZE 100
#define LISTINCREMENT 10

typedef int ElementType;
typedef struct Llist *SqList;

struct Llist
{

    ElementType* elem;
    int length;
    int listsize;
};

SqList InitList(SqList L)
{
    L=(SqList)malloc(sizeof(SqList));
    L->elem=(ElementType*)malloc(LISTSIZE*sizeof(ElementType));
    
    if(L->elem==NULL)
    {
        printf("out of space\n");
    }
    L->length=0;
    L->listsize=LISTSIZE;
    return L;
} 

void DestroyList(SqList L)
{
    L->length=0;
    L->listsize=LISTSIZE;
    free(L->elem);
    L->elem=NULL;
}

void ClearList(SqList L)
{
    L->length=0;
}

bool IsEmpty(SqList L)
{
    if(L->length==0)return true;
    else return false;
}

int Getlength(SqList L)
{
    return L->length;
}

ElementType GetElement(SqList L,int i)
{
    if(i<=0||i>L->length)
    {
        printf("error!\n");
        return 0;
    }
    return L->elem[i];
}

SqList InsertList(SqList L,int i,ElementType X)
{
    if(i<=0||i>L->length+1)
    {
        printf("error!\n");
        return L;
    }
    if(L->length>=L->listsize)
    {
        ElementType *newbase;
        newbase=(ElementType*)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(ElementType));
        if(!newbase)
        {
            printf("out of space!\n");
            return L;
        }
        L->elem=newbase;
        L->listsize+=LISTINCREMENT;
    }
    int p;
    for(p=L->length-1;p>=i-1;p--)
    {
        L->elem[p+1]=L->elem[p];
    }
    L->elem[p+1]=X;
    L->length++;
    return L;

}

SqList DeleteList(SqList L,int i)
{
    if(i<1||i>L->length)
    {
        printf("error!\n");
        return L;
    }
    int p=i;
    for(p;p<=L->length-1;p++)
    {
        L->elem[p-1]=L->elem[p];
    }
    L->length--;
    return L;
}

void Print(SqList L)
{
    for(int i=0;i<L->length;i++)
    {
        cout<<L->elem[i]<<" ";
    }
}

int main()
{
    SqList L;
    L=InitList(L);
    L=InsertList(L,1,1);
    L=InsertList(L,1,2);
    L=InsertList(L,1,3);
    L=InsertList(L,1,4);
    Print(L);
    L=DeleteList(L,2);
    Print(L);
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青云遮夜雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值