支持创建,取值,查找,插入,删除,清空的操作
#include<bits/stdc++.h>
//#include <iostream>
//#pragma GCC optimize(2)
using namespace std;
#define maxn 100
#define inf 1e18
typedef long long ll;
const ll mod = 1e9+7;
ll key;
struct ElemType
{
ll num;
bool operator == (const ElemType t) const
{
return t.num == num;
}
};
typedef struct
{
ElemType *elem;
int lenth;
}SqList;
ll InitList(SqList &L)
{
L.elem = new ElemType[maxn];
if(!L.elem)
exit(-2);
L.lenth = 0;
return 1;
}
ll GetElem(SqList L,ll i,ElemType &e)
{
if(i<1 || i>L.lenth)
return 0;
e = L.elem[i-1];
return 1;
}
ll LocateElem(SqList L,ElemType &e)
{
for(ll i = 0; i < L.lenth; i++)
if(L.elem[i] == e)
return i+1;
return 0;
}
ll Lclear(SqList &L)
{
L.lenth = 0;
return 1;
}
ll ListInesrt(SqList &L,ll i,ElemType e)
{
if(i<1 || i>L.lenth+1)
return 0;
if(L.lenth == maxn)
return 0;
for(ll j = L.lenth-1; j >= i-1; j--)
{
L.elem[j+1] = L.elem[j];
}
L.elem[i-1] = e;
L.lenth ++;
return 1;
}
ll ListDelete(SqList &L,ll i)
{
if(i<1 || i>L.lenth)
return 0;
for(ll j = i-1; j <= L.lenth-1; j++)
L.elem[j] = L.elem[j+1];
L.lenth--;
return 1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
SqList arr;
InitList(arr);
cout << "空顺序表建立成功!" << endl;
while(true)
{
ll k;
cout << "如果你想结束本程序,请输入0,否则输入1" <<endl;
cin >> k;
if(k == 0)
break;
else if(k == 1)
{
cout << "取值操作请输入1" << endl;
cout << "查找操作请输入2" << endl;
cout << "插入操作请输入3" << endl;
cout << "删除操作请输入4" << endl;
cout << "清空操作请输入5" << endl;
cin >> key;
if(key == 1)
{
cout << "请输入您想要从顺序表中取第几个值" << endl;
ll loc;
ElemType num;
cin >> loc;
if ( GetElem(arr,loc,num)!=0 )
cout << "取值成功,取出的值为" << num.num << endl;
else
cout << "取值失败,请检查输入的位置是否正确" << endl;
}
else if(key == 2)
{
cout << "请输入您想要查找的值" << endl;
ll loc;
ElemType num;
cin >> num.num;
loc = LocateElem(arr,num);
if(loc!=0)
cout << "查找成功,此值在顺序表的第" << loc << "个位置" << endl;
else
cout << "查找失败,顺序表中无此值" << endl;
}
else if(key == 3)
{
cout << "请输入您想要插入的位置与插入的值" << endl;
ll loc;
ElemType num;
cin >> loc >> num.num;
if( ListInesrt(arr,loc,num) )
cout << "插入成功" << endl;
else
cout << "插入失败,请检查输入的位置是否正确" << endl;
}
else if(key == 4)
{
cout << "请输入您想要删除的位置" << endl;
ll loc;
cin >> loc;
if( ListDelete(arr,loc) )
cout << "删除成功" << endl;
else
cout << "删除失败,请检查输入的位置是否正确" << endl;
}
else if(key == 5)
{
Lclear(arr);
cout << "清空成功" << endl;
}
}
}
return 0;
}
本文详细介绍了使用C++实现顺序表的基本操作,包括初始化、取值、查找、插入、删除和清空等,并通过一个交互式的主函数展示了如何进行这些操作。文章提供了完整的代码示例,有助于理解和学习数据结构中的顺序表概念。

被折叠的 条评论
为什么被折叠?



