顺序表的初始化、插入、删除

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
//#include <conio.h>

using namespace std;

typedef struct
{
    int data;
    char name[100];
} ElemType;
typedef int Status;
#define OK 1
#define OVERFLOW -2
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct
{
    ElemType *elem;
    int length;
    int listsize;
} Sqlist;


Status InitList(Sqlist * L);
Status ListInsert(Sqlist *L,int i,ElemType e);
Status ListDelete(Sqlist *L,int i,ElemType *e);
Statys LocateElem(Sqlist L,ElemType e);


Status InitList(Sqlist * L) //线性表的初始化
{
    L->elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
    if(!L->elem)
    {
        cout<<"OVERFLOW"<<endl;
        return ERROR;
    }
    L->length=0;
    L->listsize=LIST_INIT_SIZE;
    return OK;
}

Status ListInsert(Sqlist *L,int i,ElemType e)  //线性表的插入
{
    ElemType *newbase,*q,*p;
    int j;
    if(i<1||i>L->length+1)
        return ERROR;
    if(L->length>=L->listsize)
    {
        newbase=(ElemType *)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(ElemType));
        if(!newbase)
        {
            cout<<"空间已满"<<endl;
            return ERROR;
        }
        L->elem=newbase;
        L->listsize=L->listsize+LISTINCREMENT;
    }
    for(j=(L->length);j>=i;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)  //线性表的删除
{
    ElemType *p,*q;
    int j;
    if(i<1||i>L->length)
        return ERROR;
    *e=L->elem[i-1];
    for(j=i;j<L->length;j++)
        L->elem[j-1]=L->elem[j];
    --L->length;
    return OK;

}
Statys LocateElem(Sqlist L,ElemType e)  //查找
{
     ElemType *p;
     int i=1;
     p=L.elem;
     while(i<=L.length&&(*p++)!=e)
             ++i;
     if(i<=L.length)
        return i;
     else
        return 0;
}
int main()
{
    Sqlist Lst;
    int n,m;
    ElemType e;
    cout<<"用户自己定义n组数据:"<<endl;
    cin>>n;  //用户自己定义n组数据
    cout<<"用户自己定义删除的m"<<endl;
    cin>>m;   //用户自己定义删除 m
    if(InitList(&Lst)==OK)
    {
        for(int i=1; i<=n; i++)
        {
            cin>>e.data>>e.name;
            if(ListInsert(&Lst,i,e)!=OK)
                break;
        }
    }
    cout<<endl;
    for(int i=0; i<Lst.length; i++)
        printf("i,e.data=%d,%d %s\n",i+1,Lst.elem[i].data,Lst.elem[i].name);
    getchar();
    getchar();
    if(ListDelete(&Lst,m,&e)==OK)
    {
        printf("delete_elem.data=%d %s\n",e.data,e.name);
    }
    getchar();
    for(int i=0; i<Lst.length; i++)
        printf("i,e.data=%d,%d %s\n",i+1,Lst.elem[i].data,Lst.elem[i].name);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值