数据结构与算法之顺序表的实现

实现代码为C语言,教材为清华大学严蔚敏版。

#include<stdio.h>
 #include<stdlib.h>
 #define OK 1
 #define ERROR 0
 #define MAXSIZE 100
 typedef int Status;
 typedef int ElemType;
 typedef struct
 {
     ElemType *elem;//*elem存储空间的基地址
     int length;

 }Sqlist;
 Sqlist L;
 Status Initlist(Sqlist &L)//构造一个空的线性表
 {
     L.elem=new ElemType[MAXSIZE];
     if(!L.elem)
     return ERROR;
     L.length=0;
     return OK;

 }

 int GetElem(Sqlist L,int i,ElemType &e)
 {
     if(i<1||i>L.length)
     return ERROR;
     e=L.elem[i-1];//第i-1个单元存储着第i个数据
     return OK;

 }
 
 //清空线性表
 int ClearList(Sqlist &L)
 {
     L.length=0;
     return OK;
 }

//判断线性表是否为空
int IsEmpty(Sqlist L)
{
    if(L.length==0)
    return OK;
}

//获取线性表的长度
int Getlength(Sqlist L)
{
    return(L.length);
}

int DestoryList(Sqlist &L)
{
    if(L.elem)
    delete L.elem;
    return OK;

}

Status locateElem(Sqlist &L,ElemType e )
{
    int i;
    for(i=0;i<L.length;i++)
    {
        if(L.elem[i]==e)
        return i+1;

    }

    return ERROR;
}

Status ListInsert(Sqlist &L,int i,ElemType e)
{
    if(i<1||i>L.length+1)
    return ERROR;
    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;


}


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

    
}

//主函数测试
int main()
{
    if(Initlist(L))
    {
        printf("Initlist success!\n");
        
        int i;
        ElemType e;
        for(i=0;i<10;i++)
        {
            ListInsert(L,i+1,i);//测试InsertList函数
            
           
        }
       
        
        printf("Length is %d\n",Getlength(L));

        if(GetElem(L,1,e))
        printf("the first element %d\n",e);
        else
        printf("element is not exist\n");
        if(locateElem(L,2))
        printf("the element is locate at %d\n",locateElem(L,2));
        else
        {
            printf("the element is not exist");

        
        }
        if(ListDelete(L,2))
        printf("delect ok");

        if(IsEmpty(L))
        printf("List is empty");
        else
        printf("list is not empty");

        if(DestoryList(L))
        printf("destory success\n");
        if(ClearList(L))
        printf("clear success");

    
    }
    return 0;
}


  




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值