#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; typedef int ElemType; typedef int Status; #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 ElemType * newbase,*p,*q; //顺序表的结构描述 typedef struct{ ElemType *elem; int length; int listsize; }SqList; //顺序表的初始化 Status InitList_Sq(SqList &L){ //构造一个空的线性表L L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(!L.elem)exit(OVERFLOW); //存储分配失败 L.length = 0; //空表长度为0 L.listsize = LIST_INIT_SIZE; //初始存储容量 return OK; }//InitList_Sq //顺序表的建立 void Creat_Sq(SqList &L){ int i,n; cout<<"请输入顺序表的元素个数:"; cin>>n; for(i=0;i<n;i++){ cout<<"请输入第 "<<(i+1)<<" 个元素:"; cin>>L.elem[i]; L.length++; } } //顺序表的显示 void Show_Sq(SqList L){ for(int i=0;i<L.length;i++){ cout<<L.elem[i]<<" "; } cout<<endl; } //顺序表的插入 Status ListInsert_Sq(SqList &L,int i,ElemType e){ if(i<1||i>L.length+1){ cout<<"i值不合法"<<endl; return ERROR; } if(L.length>=L.listsize){ newbase = (ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType)); if(!newbase)exit(OVERFLOW); L.elem = newbase; L.listsize += LISTINCREMENT; } q = &(L.elem[i-1]); for(p = &(L.elem[L.length-1]);p>=q;--p){ *(p+1) = *p; } *q = e; ++L.length; return OK; } //顺序表的删除 Status ListDel_Sq(SqList &L,int i,ElemType e){ if(i<1||i>L.length+1){ cout<<"i值不合法"<<endl; return ERROR; } q = &(L.elem[L.length-1]); for(p=&(L.elem[i-1]);p<=q;p++){ *p=*(p+1); } e=*q; --L.length; return OK; } //顺序表的修改 Status ListUpdate_Sq(SqList &L,int i,ElemType e){ if(i<1||i>L.length+1){ cout<<"i值不合法"<<endl; return ERROR; } L.elem[i-1] = e; return OK; } int main() { SqList L; InitList_Sq(L); Creat_Sq(L); Show_Sq(L); int num=0,i; ElemType e; bool flag = true; while(flag){ cout<<"1.插入 "<<"2.删除 "<<"3.修改 "<<endl; cout<<"请输入要执行操作的序号:"; cin>>num; if(num>=1&&num<=3){ flag=false; }else{ cout<<"输入非法"<<endl; } } switch(num){ case 1 :{ cout<<"请输入要插入的位置:"; cin>>i; cout<<"请输入要插入的数:"; cin>>e; ListInsert_Sq(L,i,e); }break; case 2 :{ cout<<"请输入要删除的位置:"; cin>>i; ListDel_Sq(L,i,e); }break; case 3 :{ cout<<"请输入要修改的位置:"; cin>>i; cout<<"请输入修改成的数:"; cin>>e; ListUpdate_Sq(L,i,e); }break; } Show_Sq(L); return 0; }
时间: 2024-10-06 14:35:20