顺序表的操作

来源:互联网 发布:mac 网页添加到收藏夹 编辑:程序博客网 时间:2024/04/29 17:55

编程实现顺序表的以下基本操作:建立顺序表,修改顺序表,插入顺序表,删除顺序表。

#include <iostream>#include <stdio.h>#include <stdlib.h>#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define OK 1#define OVERFLOW -2#define ERROR 0using namespace std;typedef struct{    int *elem;    int length;    int listsize;} SqList;int InitList_Sq(SqList &L){    L.elem=(int *)malloc(LIST_INIT_SIZE*sizeof(int));    if(!L.elem)        exit(OVERFLOW);    L.length=0;    L.listsize=LIST_INIT_SIZE;    return OK;}int ListInsert_Sq(SqList &L,int i,int e)//在第i位置插入e{    if(i<1||i>L.length+1)        return ERROR;    if(L.length>=L.listsize)    {        int *newbase;        newbase=(int*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int));        if(!newbase)            exit(OVERFLOW);        L.elem=newbase;        L.listsize+=LISTINCREMENT;    }    int *p,*q;    q=&(L.elem[i-1]);    for(p=&(L.elem[L.length-1]); p>=q; p--)        *(p+1)=*p;    *q=e;    ++L.length;    return OK;}int ListAlter_Sq(SqList &L,int i,int j,int &e)//修改第i个元素为j值,并用e返回i值{    if(i<1||i>L.length)        return ERROR;    e= L.elem[i-1];    L.elem[i-1]=j;    return OK;}int ListDelete_sq(SqList &L,int i,int &e)//删除第i个元素,删除元素用e返回{    if((i<1)||(i>L.length))        return ERROR;    int *p;    p=&(L.elem[i-1]);    e=*p;    int* q;    q=L.elem+L.length-1;    for(++p; p<=q; ++p)        *(p-1)=*p;    --L.length;    return OK;}void Get(SqList L)//输出表内所有元素{    cout<<"当前列表:"<<endl;    for(int i=0; i<L.length; i++)    {        cout<<L.elem[i]<<" ";    }    cout<<endl;}int main(){    SqList L;    while(true)    {        cout<<"新开始:"<<endl;        InitList_Sq(L);        cout<<"输入元素个数:"<<endl;        int index=1;        int n;        cin>>n;        cout<<"输入列表元素:"<<endl;        int ele;        for(int i=0; i<n; i++)        {            cin>>ele;            ListInsert_Sq(L,index++,ele);        }        Get(L);        int i,j;        cout<<"你想要插入的元素位置是:"<<endl;        cin>>i;        cout<<"插入元素的值是:"<<endl;        cin>>j;        if(ListInsert_Sq(L,i,j))        {            Get(L);        }        else            cout<<"操作失败!"<<endl;        cout<<"你想要删除的元素位置是:"<<endl;        cin>>i;        int e;        if(ListDelete_sq(L,i,e))            cout<<"被删除元素的值:"<<endl<<e<<"\n"<<endl;        else            cout<<"操作失败!\n"<<endl<<endl;;        Get(L);        cout<<"你想要替换的元素位置:"<<endl;        cin>>i;        cout<<"新元素的值是:"<<endl;        cin>>j;        if(ListAlter_Sq(L,i,j,e))            cout<<"被替换元素的值是"<<endl<<e<<"\n"<<endl;        else            cout<<"操作失败!\n"<<endl;;        Get(L);        cout<<endl;    }    return 0;}


0 0
原创粉丝点击