线性表-插入-删除

#include<stdio.h>
#define error 0
#define ok 1
#define true 1
#define false 0
#define maxn 100
typedef int Status;
typedef int ElemType;

typedef struct
{
    ElemType elem[maxn];
    int length;
} SqList;

Status ListInsert(SqList &L, int i, ElemType e)///插入函数
{
    int j;
    if(L.length==maxn)return error;
    if(i<1 || i>L.length+1)return error;

    for(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, ElemType *e)///删除函数
{
    int j;
    if(L.length==0)return error;
    if(i<1 || i>L.length)return error;

    *e=L.elem[i-1];
    for(j=i-1; j<L.length; j++)
        L.elem[j]=L.elem[j+1];

    L.length--;
    return ok;
}

Status InitList(SqList &L)
{
    L.length=0;
    return ok;
}

void Trans(SqList L)
{
    int j;
    for(j=0; j<L.length; j++)
        printf("%d%c", L.elem[j], j==L.length-1?'\n':' ');
}
int main()
{
    SqList L;
    int a;

    ///1)初始化顺序表
    InitList(L);

    ///2)插入一些元素: 12,23,34,45
    ListInsert(L,1,12);
    ListInsert(L,1,23);
    ListInsert(L,1,34);
    ListInsert(L,1,45);
    Trans(L);
    ListDelete(L, 1, &a);

    printf("\n删除的元素:\n%d\n", a);
    Trans(L);
    return 0;
}

 

posted @ 2016-09-12 20:29  爱记录一切美好的微笑  阅读(211)  评论(0编辑  收藏  举报