线性表:0个或多个元素的有限集合。
顺序存储结构:一维数组
优点:随机访问快速,逻辑上相邻的元素,物理上也相邻,无须为元素之间的逻辑关系额外增加存储空间
缺点:插入和删除需要移动大量元素 很麻烦,当线性表长度变化很大时,难以确定存储空间的容量,容易造成存储空间的碎片化
实现:
seqlist.h
//
// Created by shuai on 1/20/19.
//
/*
仅仅是简单实现了功能,对于输入出错等没有考虑,会有bug,但是就是练个手呗
以int类型为原型,可以加上类模板,但是没有必要
*/
#ifndef INC_001_SEQLIST_H
#define INC_001_SEQLIST_H
#include "iostream"
using namespace std;
const int MaxSize = 100;
//template <class T>
class seqlist {
public:
seqlist() { length = 0;};
seqlist(int a[], int n);
~seqlist();
bool listEmpty();
int len(){return length;};
int getElem(int i);
int locateElem(int x);
void listInsert(int i, int elem);
int listDelete(int i);
void showlist();
private:
int data[MaxSize];
int length;
};
#endif //INC_001_SEQLIST_H
seqlist.cpp:
//
// Created by shuai on 1/20/19.
//
#include "seqlist.h"
seqlist::seqlist(int *a, int n) {
for(int i = 0;i < n;i++){
data[i] = a[i];
}
length = n;
}
int seqlist::getElem(int i) {
return data[i - 1];
}
int seqlist::listDelete(int i) {
int tmp = data[i - 1];
for(int k = i - 1;k < length - 1;k++)
data[k] = data[k + 1];
length--;
return tmp;
}
bool seqlist::listEmpty() {
if(length == 0)
return true;
else
return false;
}
void seqlist::listInsert(int i, int elem) {
//data[i - 1] = elem;
for(int k = length;k >= i;k--)
data[k] = data[k - 1];
data[i - 1] = elem;
length++;
}
int seqlist::locateElem(int x) {
for(int i = 0;i < length;i++){
if(data[i] == x)
return i + 1;
}
return -1;
}
seqlist::~seqlist() {
length = 0;
//free(data);
}
void seqlist::showlist() {
for(int i = 0;i < length;i++)
cout << data[i] << " ";
cout << endl;
}
main.cpp:
#include <iostream>
#include "seqlist.h"
using namespace std;
int main() {
seqlist s;
for(int i = 0;i < 20;i++)
s.listInsert(i + 1, i + 23);
cout << s.len() << endl;
s.showlist();
s.listInsert(10,55);
s.showlist();
cout << s.locateElem(40) << endl;
cout << s.listDelete(3) << endl;
s.showlist();
return 0;
}