• 欢迎光临~

# C++实现线性表的操作——顺序存储结构

## 建立顺序表

``````typedef struct
{
int data[MAXSIZE];
int length = 0;
}sqlist;
``````

## 初始化

``````int initList(sqlist & l, int n)
{
for (int i = 0; i < n; ++i)
{
cout << "请输入第" << i << "个元素：" ;
cin >> l.data[i];
++l.length;
}

return 1;
}
``````

## 输出

``````int displayList(sqlist l)
{
cout << "顺序表的内容为：";
for (int i = 0; i < l.length; ++i)
{
cout << l.data[i];
}
cout << endl;

return 1;
}
``````

## 查找元素

``````int findList(sqlist l)
{
int index = 0;
cout << "请输入要查找的元素的位置：";
cin >> index;
if (index < 0 || index > l.length - 1)
{
return 0;
}
else
{
cout << l.data[index] << endl;
}

return 1;
}
``````

## 插入元素

``````int insertList(sqlist & l)
{
int index = 0;
int element = 0;
cout << "请输入要插入的位置：";
cin >> index;
cout << "请输入要插入的元素：";
cin >> element;

if (index < 0 || index > l.length - 1)
{
return 0;
}
else
{
for (int i = l.length - 1; i >= index; --i)
{
l.data[i + 1] = l.data[i];
}
l.data[index] = element;
}
++l.length;

return 1;
}
``````

## 删除元素

``````int deleteList(sqlist & l)
{
int index = 0;
cout << "请输入要删除的元素位置：";
cin >> index;

if (index < 0 || index > l.length - 1)
{
return 0;
}

for (int i = index; i < l.length - 1; ++i)
{
l.data[i] = l.data[i + 1];
}
--l.length;

return 1;
}
``````