#include <iostream>
#include <algorithm>
using namespace std;
#define Maxsize 10 //代表该数组的空间
typedef struct {
int length;//用来存储数组元素的个数
int data[Maxsize];//数组本体
}SeqList;
void InitList(SeqList &L) //顺序表的初始化
{
for (int i = 0; i < 10; i++) L.data[i] = 0;
L.length = 0;
}
bool InsertList(SeqList &L, int e, int num)//在第e个位置插入一个元素num
{
if (e<1 || e>L.length+1) return false;//判断插入位置是否合理
if (L.length > Maxsize) return false;//判断数组中元素的个数是否超过数组的容量
//实现插入操作,由于数组的局限性,在顺序表中添加一个元素需要先将待插位置后面的所有元素依次往后移动一位
for (int i = L.length; i >= e; i--)
{
L.data[i] = L.data[i - 1];
}//移位
L.data[e - 1] = num;//插入
L.length++;//数组元素+1
return true;
}
bool DeleteList(SeqList& L, int position ,int &e)
{
if (position<1 || position>L.length) return false;//判断删除的位置是否合理
e = L.data[position - 1];//将待删除的元素传给e进行保存,用于返回
实现删除操作,由于数组的局限性,在顺序表中删除一个元素需要将待删元素之后的每一个元素向前移动一位
for (int i = position-1; i < L.length; i++)//删除操作
{
L.data[i] = L.data[i + 1];
}
L.length--;
return true;
}
int SerachListByPosition(SeqList L,int position)//查找元素(按值查找) 时间复杂度为O(1) 返回该位置所表示的元素
{
return L.data[position - 1];
}
int SerachListByNum(SeqList L, int num)//查找元素(按位查找) 时间复杂度为O(n) 返回该元素所在的位置
{
for (int i = 0; i < L.length; i++)
{
if (L.data[i] == num) return i + 1;
}
return -1;
}
int main()
{
SeqList L;
InitList(L);
while (true)
{
int choice;
cout << "1.插入一个元素"<<endl;
cout << "2.遍历整个顺序表"<<endl;
cout << "3.删除一个元素" << endl;
cout << "4.查找元素(按位查找)" << endl;
cout << "5.查找元素(按值查找)" << endl;
cout << "5.退出程序"<<endl;
cout << "请选择功能"<<endl;
cin >> choice;
if (choice == 1)// 在第e个位置插入一个元素num
{
int e, i;
cin >> e >> i;
if (InsertList(L,e,i)) cout << "添加成功";
else cout << "您的输入有误,添加失败";
cout << endl;
}
else if (choice == 2)//对顺序表进行遍历
{
for (int i = 0; i < L.length; i++) cout << L.data[i] << " ";
cout << endl;
}
else if (choice == 3)//删除数组中第position个元素
{
int position;
cin >> position;
int e = -1;//用来接受被删除的元素
if (DeleteList(L, position, e)) cout << "删除成功";
else cout << "您的输入有误,删除失败";
cout << endl;
}
else if (choice == 4)//4.查找元素(按位查找)
{
int position;
cin >> position;
int x = SerachListByPosition(L, position);
printf("第%d个数是%d", position, x);
cout << endl;
}
else if (choice == 5)//5.查找元素(按值查找)
{
int num;
cin >> num;
int x = SerachListByNum(L, num);
printf("%d是这个数组的第%d个元素", num, x);
}
else if (choice == 6)//退出程序
{
break;
}
cout << endl;
}
return 0;
}
顺序表的代码实现(包括创建,添加,删除以及查询操作(按值查找和按位查找))
于 2023-12-09 16:13:35 首次发布