DataStructure-用数组实现List

表的基本概念
表(线性表),是一种非常灵活的结构,可以根据自己的需要改变表的长度,也可以在其中任何位置对元素进行访问、插入、删除等操作。另外还可以将多个表连接成一个表,或者把一个表拆分多个表。

表的图示结构
这里写图片描述

用数组实现表

#include <stdio.h>
#include <malloc.h>
typedef  int ListItem;//将int类型取别名为ListItem,让代码便于读
typedef struct alist *List;
typedef struct alist
{
    int n;//表的长度
    int maxsize;//表的最大长度
    ListItem *table;//表元素数组

}Alist;

List ListInit(int size){//初始化List,参数为表长度
    List L=malloc(sizeof *L);
    L->table=malloc(size*sizeof(ListItem));//分配内存
    L->maxsize=size;
    L->n=0;
    return L;
}
int ListEmpty(List L){//判断表是否为空
    return L->n==0;
}

int ListLength(List L){//返回当前表长度
    return L->n;
}

int ListLocate(ListItem x,List L){//返回元素x在表中的位置
    int i;
    for(i=0;i<L->n;i++){
        if(L->table[i]==x) return ++i;
    }
    return 0;
}
int ListRetrieve(int k,List  L){//返回表L中k处的元素
    if(k<1 || k>L->n) printf("out of bounds");
    return L->table[k-1];
}


void ListInsert(int k,ListItem x,List L){//插入函数,将元素x插入位置k处,k+1之后位置的元素向右移
    int i;
    if(k<0 || k>L->n+1) {
        printf("out of bounds!");
    }
    if(L->n==L->maxsize) printf("out of memory!");
    for(i=L->n-1;i>=k;i++){
        L->table[i+1]=L->table[i];
    }
    L->table[k-1]=x;
    L->n++;
}
ListItem ListDelete(int k,List L){//删除位置K处的元素,将K+1之后的向左移
    int i;
    ListItem x;
    if(k<1||k>L->n) printf("out of bounds!");
    x=L->table[k-1];
    for(i=k;i<L->n;i++) L->table[i-1]=L->table[i];
    L->n--;
             return x;
}
void printList(List L){//遍历列表L,打印
              int i;
     for(i=0;i<L->n;i++){
        printf("%d\n",L->table[i] );
     }
}


void main(){
    List  L=ListInit(10);

    ListInsert(1,1,L);
    ListInsert(2,2,L);
    ListInsert(3,3,L);
    ListInsert(4,4,L);
    ListInsert(5,5,L);
    ListInsert(6,6,L);
    ListInsert(7,7,L);

    ListDelete(3,L);

    printList(L);
    printf("element %d -> %d\n",5,ListLocate(5,L) );
    printf("locate %d -> %d\n",5,ListRetrieve(5,L) );
    printf("ListLength ->%d\n",ListLength(L) );
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值