#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType;
typedef struct
{
ElemType *elem; //线性表的基地址
int length; //当前长度
int listsize;//当前分配的存储容量
}SqList;
SqList L;
int InitList_Sq(SqList &L)
{
L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem) {
exit(0);
cout<<"存储分配失败"<<endl;
}
L.length=0;
L.listsize=LIST_INIT_SIZE;
return 1;
}
//插入
int ListInsert_Sq(SqList &L,int i,ElemType e)
// 在顺序表L中第i个位置之前插入新元素e
{
if(i<1||i>L.length+1)
{
cout<<"插入的位置不合法"<<endl;
return -1;
}
if(L.length>=L.listsize)//当前的存储空间已满 从新分配空间
{
ElemType *newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
if(!newbase)
{
cout<<"从新分配内存失败"<<endl;
exit(-1);
}
}
ElemType *q=&(L.elem[i-1]),*p;
for(p=&(L.elem[L.length-1]);p>=q;--p) *(p+1)=*p;
*q=e;
++L.length;
return 1;
}
//删除
int ListDelete_Sq(SqList &L,int i,ElemType &e)
{
//判断i是否合法
if((i<1)||(i>L.length)) {
cout<<"删除的位置不存在"<<endl;
return -1;
}
ElemType *p=&(L.elem[i-1]),*q;
e=*p;
q=L.elem+L.length-1;
for(++p;p<=q;++p) *(p-1)=*p;
--L.length;
return 1;
}
//比较函数
int Compare(ElemType a,ElemType e)
{
if(a==e)
return 1;
else
return 0;
}
//查找
int LocateElem_Sq(SqList L,ElemType e)
{
int i=1;
ElemType *p;
p=L.elem;
while(i<=L.length && !Compare(*p++,e)) i++;
if(i<=L.length)
return i;
else
{
cout<<"没有找到"<<endl;
return 0;
}
}
void PaintLst_Sq(SqList L)
{
for(int i=0;i<L.length;i++)
cout<<L.elem[i]<<" ";
cout<<endl;
}
int main()
{
cout << "程序开始!!" << endl;
if(InitList_Sq(L)==1)
cout<<"初始化成功"<<endl;
int n;
cout<<"请输入初始化的序列个数:";
cin>>n;
int k;
for(int i=0;i<n;i++)
{
cin>>k;
ListInsert_Sq(L,i+1,k);
}
cout<<"此时的线性表是:"<<endl;
PaintLst_Sq(L);
int cn,locate;
ElemType e;
cout<<"要插入的值得次数"<<endl;
cin>>cn;
while(cn--)
{
cout<<"输入插入的位置和值"<<endl;
cin>>locate>>e;
ListInsert_Sq(L,locate,e);
cout<<"此时的线性表是:"<<endl;
PaintLst_Sq(L);
}
cout<<"要删除的次数"<<endl;
cin>>cn;
while(cn--)
{
cout<<"要删除的位置:"<<endl;
cin>>locate;
ListDelete_Sq(L,locate,e);
cout<<"删除的元素是:"<<endl;
cout<<"此时的线性表是:"<<endl;
PaintLst_Sq(L);
}
cout<<"要查找的次数:"<<endl;
cin>>cn;
while(cn--)
{
cout<<"要查找的元素:"<<endl;
cin>>e;
locate=LocateElem_Sq(L,e);
cout<<"元素"<<e<<" 的位置在: "<<locate<<"处"<<endl;
cout<<"此时的线性表是:"<<endl;
PaintLst_Sq(L);
}
return 0;
}
运行结果