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

来源:互联网 发布:sketch windows 编辑:程序博客网 时间:2024/06/05 13:28
#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 10typedef 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
原创粉丝点击