C++ 顺序表(动态分配)
原创
©著作权归作者所有:来自51CTO博客作者Dragon水魅的原创作品,请联系作者获取转载授权,否则将追究法律责任
总结归纳
- 动态分配对内存有着更大的控制权,但也会花费相应的时间。
- 顺序表的查找时间复杂度为O(1),这是单链表所不具备的。
- 顺序表的插入,要从后往前遍历,因为数据要后移;顺序表的删除,要从前往后遍历,因为数据要前移。
代码实现
#define InitSize 5
#include <iostream>
#include <stdio.h>
using namespace std;
struct SqList {
int *data;
int MaxSize;
int length;
};
void InitList(SqList &L) {
L.data = new int[InitSize];
L.MaxSize = InitSize;
L.length = 0;
}
void AssginList(SqList &L) {
for (int i = 0; i < InitSize; i++) {
L.data[i] = i;
L.length++;
}
}
int Length(SqList &L) { return L.length; }
void IncreaseSize(SqList &L, int len) {
int *p = L.data;
L.data = new int[L.MaxSize + len];
for (int i = 0; i < L.length; i++) {
L.data[i] = p[i];
}
L.MaxSize = L.MaxSize + len;
delete p;
}
int GetElem(SqList &L, int i) {
return L.data[i - 1];
}
int LocateElem(SqList &L, int i) {
for (int j = 0; j < L.length; j++) {
if (L.data[j] == i) {
return j + 1;
}
}
return 0;
}
void ListInsert(SqList &L, int i, int e) {
if (L.length = L.MaxSize) {
IncreaseSize(L, 1);
}
for (int j = L.length; j >= i; j--) {
L.data[j] = L.data[j - 1];
}
L.data[i - 1] = e;
L.length++;
}
bool ListDelete(SqList &L, int i, int &e) {
if (i < 0 || i > L.length) {
return false;
}
e = L.data[i - 1];
for (int j = i; j < L.length; j++) {
L.data[j - 1] = L.data[j];
}
L.data[L.length] = 0;
L.length--;
return true;
}
void PrintList(SqList &L) {
for (int i = 0; i < L.length; i++) {
cout << L.data[i] << " ";
}
cout << endl;
}
int main() {
struct SqList L;
InitList(L);
AssginList(L);
PrintList(L);
int len = Length(L);
cout << "表长:" << len << endl;
ListInsert(L, 3, 44);
Length(L);
PrintList(L);
int e = -1;
if (ListDelete(L, 3, e)) {
cout << "删除的数据:" << e << endl;
PrintList(L);
} else {
cout << "删除数据超出范围" << endl;
}
int locate_elem;
locate_elem = LocateElem(L, 3);
cout << "查找到的位置:" << locate_elem << endl;
int get_elem;
get_elem = GetElem(L, 3);
cout << "查找到的数据:" << get_elem << endl;
}