顺序存储结构的优缺点:
一、
优点
1.
逻辑相邻,物理相邻
2.
易于随机存取任一元素
3.
存储空间使用紧凑
二、
缺点
1.
插入、删除
操作需要移动大量的元素
2.
预先分配空间需按最大空间分配,利用不充分
3.
表容量难以扩充
整体代码:
#include<iostream>
using namespace std;
//顺序表
template<typename ElemType>
struct SeqList {
ElemType* items;
int length;
int capacity;
SeqList(){}
void InitSeq(int c) {
cout << "初始化顺序表" << endl;
capacity = c;
length = 0;
items = new ElemType[capacity];
}
~SeqList() {
cout << endl;
cout << "析构顺序表" << endl;
length = capacity = 0;
free(items);
}
int Insert(ElemType e)
{
if (length < capacity) {
items[length] = e;
length++;
}
else {
cout << "sorry,已经满了" << endl;
}
return 1;
}
void Delete(int index) {
cout << "已经删除了" << endl;
for (int i = index; i < length-1; i++)
items[i] = items[i + 1];
length--;
}
int serch(ElemType e) {
for (int i = 0; i < length; i++)
{
if (items[i] == e) {
cout << "成功查找到" << e << endl;
return 1;
}
}
cout << "没有查找到" << endl;
return 1;
}
int set(ElemType e, int index) {
items[index] = e;
return 1;
}
void output() {
for (int i = 0; i < length; i++) {
cout << items[i] << " ";
}
}
};
int main() {
SeqList<int>s;
s.InitSeq(5);
for (int i = 1; i <= 6; i++)
s.Insert(i);
s.output();
s.Delete(2);
s.output();
s.serch(3);
s.output();
s.set(9, 2);
s.output();
return 0;
}
输出结果:
初始化顺序表
sorry,已经满了
1 2 3 4 5 已经删除了
1 2 4 5 没有查找到
1 2 4 5 1 2 9 5
析构顺序表