仅供个人复习
#define MAXSIZE 100
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef struct
{
int* elem;
int length;
}SqList;
bool Init(SqList& L)
{
L.elem = new int[MAXSIZE];
if(!L.elem) exit(OVERFLOW);//内存分配失败,报告问题
L.length = 0;
return true;
}
void Elem(SqList& L)
{
cout<<"输入顺序表长度:"<<'\n';
int n;
cin>>n;
cout<<"输入元素的值:"<<'\n';
for(int i = 0 ; i < n ; i++)
{
cin>>L.elem[i];
}
L.length = n;
}
int LocateElem(SqList& L , int e)//查找元素
{
for(int i = 0 ; i < L.length ; i++)
{
if(L.elem[i] == e) return i+1;
}
return 0;
}
int ListInsert(SqList& L,int i,int e) // i值的合法范围是1<=i<=n+1,合法返回1,否则返回0
{
if(i<1 || i>L.length+1) return 0;
if(L.length == MAXSIZE) return 0;//存储空间已满
for(int j = L.length-1 ;j >= i - 1; j--)
L.elem[j+1] = L.elem[j];//插入位置后的元素后移
L.elem[i-1] = e;
++L.length;
return 1;
}
int Del(SqList& L , int i)//删除第i个元素
{
if(i<1 || i>L.length) return 0;
for(int j = i; j<= L.length-1 ; j++)
L.elem[j-1] = L.elem[j];
L.length--;
return 1;
}
int main()
{
SqList L;
Init(L);
Elem(L);
cout<<"查找元素e:"<<'\n';
int e;
cin>>e;
int ans = LocateElem(L,e);
if(ans)
{
cout<<"查找成功:";
cout<<ans;
}
else
{
cout<<"查找失败";
}
cout<<'\n';
cout<<"插入:"<<'\n';
cout<<"输入插入位置和数据:";
int i;
cin>>i>>e;
ans = ListInsert(L,i,e);
if(ans)
{
cout<<"插入后的元素如下:"<<'\n';
for(int i = 0 ; i < L.length ;i++)
{
cout<<L.elem[i]<<" ";
}
cout<<'\n';
}
else
{
cout<<"插入失败"<<'\n';
}
cout<<"删除第i个元素:"<<'\n';
cout<<"输入i:";
cin>>i;
ans = Del(L,i);
if(ans)
{
for(int i = 0 ; i < L.length ; i++)
cout<<L.elem[i]<<" ";
}
else
{
cout<<"删除位置不合理"<<'\n';
}
return 0;
}
数据结构第一章例题
最新推荐文章于 2024-08-16 22:20:39 发布