顺序表是用一组地址连续的存储单元依次存储线性表中的数据元素。
特点:
- 表中元素的逻辑顺序与物理顺序相同(因此插入和删除操作需要移动大量的元素)
- 随机访问
- 存储密度高(每个节点只存储数据元素)
/*
ArrayList.h
*/
#pragma once
template <class DataType>
class ArrayList
{
public:
ArrayList();
ArrayList(int capacity);
~ArrayList();
// 获取当前顺序表长度
int Length();
// 按值查询(返回位序)
int LocateElement(DataType x);
// 按位插入元素
bool Insert(DataType data, int i);
// 顺序表末尾添加元素
bool Add(DataType data);
// 判断顺序表是否为空
bool IsEmpty();
// 按位删除
bool DeleteByIndex(int i);
private:
// 初始容量
int capacity;
// 注: 线性表中元素位序从1开始, 数组中元素下标从0开始
// 顺序表长度
int length;
// 数组指针(动态分配数组)
DataType* p;
};
/*
ArrayList.cpp
*/
#include "ArrayList.h"
#include <iostream>
using namespace std;
template<class DataType>
ArrayList<DataType>::ArrayList()
{
this->capacity = 10;
this->p = new DataType[capacity];
this->length = 0;
}
/**
* 输入: 顺序表初始化容量
* 输出:
*/
template<class DataType>
ArrayList<DataType>::ArrayList(int capacity)
{
this->capacity = capacity;
this->p = new DataType[capacity];
this->length = 0;
}
template<class DataType>
ArrayList<DataType>::~ArrayList()
{
// 释放指针
delete[] p;
}
/**
* 操作:获取表长
* 输入:
* 输出: 当前顺序表长度
*/
template<class DataType>
int ArrayList<DataType>::Length()
{
return this->length;
}
/**
* 操作:按值查询
* 输入: 待查询元素
* 输出: 待查询元素在顺序表中的第一次出现的位序
* 平均时间复杂度:O(n)
*/
template<class DataType>
int ArrayList<DataType>::LocateElement(DataType x)
{
int i;
for (i = 0; i < length; i++)
{
if (x == p[i])
{
return i;
}
}
// 顺序表中不存在该元素
return 0;
}
/**
* 操作:按位插入
* 输入: 待插入元素
* 待插入位置
* 输出:
* 平均时间复杂度:O(n)
*/
template<class DataType>
bool ArrayList<DataType>::Insert(DataType data, int i)
{
if (i < 1 || i > length + 1) {
cout << "参数错误" << endl;
return false;
}
if (length >= capacity)
{
cout << "顺序表已满" << endl;
return false;
}
// 待插入位置后面的元素依次后移一位
for (int j = length; j >= i; j--)
{
p[j] = p[j - 1];
}
p[i - 1] = data;
length++;
return true;
}
/**
* 操作:表尾添加元素
* 输入: 待添加元素
* 输出:
*/
template<class DataType>
bool ArrayList<DataType>::Add(DataType data)
{
if (length >= capacity)
{
cout << "顺序表已满" << endl;
return false;
}
p[length] = data;
length++;
return true;
}
/**
* 操作:判断顺序表是否为空
* 输入:
* 输出:
*/
template<class DataType>
bool ArrayList<DataType>::IsEmpty()
{
if (length == 0)
{
return true;
}
return false;
}
/**
* 操作:按位删除
* 输入: 待删除元素的位序
* 输出:
* 平均时间复杂度:O(n)
*/
template<class DataType>
bool ArrayList<DataType>::DeleteByIndex(int i)
{
if (i < 1 || i < length)
{
cout << "参数错误" << endl;
return false;
}
// 待删除位置后面的元素依次前移一位
for (int j = i; j < length; j++)
{
p[j] = p[j + 1];
}
length--;
return true;
}