初识数据结构之顺序表,码
上说话👇。
#include<iostream>
#define maxSize 100
using namespace std;
typedef struct
{
int data[maxSize]; //存放数据
int length; //数组长度
}SqList; //构建一个结构体
void printList(SqList L) //打印数组
{
cout << "the list is:";
for(int i=0;i<L.length;i++)
cout << L.data[i] << " ";
cout << endl;
}
void addElem(SqList &L, int location, int elem) //在location位置添加元素elem
{
if(location<1 || location>L.length)
cout << "Error:out of range!";
else
{
for(int i=L.length-1;i>=location-1;i--)
L.data[i+1] = L.data[i];
L.data[location-1] = elem;
L.length++;
}
}
void deleteElem(SqList &L, int location) //删除location位置的元素
{
if(location<1 || location>L.length)
cout << "Error:out of range!";
else
{
for(int i=location-1;i<L.length-1;i++)
L.data[i] = L.data[i+1];
L.length--;
}
}
void changeElem(SqList &L, int location, int elem) //更改location处的元素 into elem
{
if(location<1 || location>L.length)
cout << "Error:out of range!";
else
L.data[location-1] = elem;
}
void searchElem(SqList L, int elem) //在数组中查询elem元素是否存在
{
int cnt = 0;
for(int i=0; i<L.length;i++)
{
if(L.data[i] == elem)
{
cout <<"The location of " <<
elem << " is " << i+1 << endl;
cnt++;
break;
}
}
if(cnt == 0)
cout << "Not found!";
}
int main()
{
SqList L;
//初始化SqList
int n;
cout << "enter the number of your list:";
cin >> n;
L.length = n;
for(int i=0;i<L.length;i++) //这里是初始化顺序表,为了方便用for循环赋值
L.data[i] = i+1;
//输出SqList
printList(L);
cout << "Add 0 in SqList at the location of 3" << endl;
addElem(L, 3, 0);
cout << "After added, the SqList's length is " << L.length << endl;
printList(L);
cout << endl;
cout << "Delete the element at the location of 3 in SqList" << endl;
deleteElem(L, 3);
cout << "After deleted, the SqList's length is " << L.length << endl;
printList(L);
cout << endl;
cout << "Change the element at the location of 2 in SqList into 0" << endl;
changeElem(L,2,0);
cout << "After changed, the SqList's length is " << L.length << endl;
printList(L);
cout << endl;
cout << "Search 5 in SqList" << endl;
searchElem(L,5);
cout << "After searched, the SqList's length is " << L.length << endl;
printList(L);
cout << endl;
}
运行如图