顺序表头文件
通过动态数组实现构造、析构、按照索引插入元素、按照索引删除元素、清空顺序表、按照索引查找元素、求顺序表的长度、判断顺序表是否为空、查找是否存在给定元素的功能。
#ifndef _Sequence_List_
#define _Sequence_List
class Sequence_List
{
public:
Sequence_List(int); //构造函数
~Sequence_List(); //析构函数
bool insert(int, int); //按位插入
bool remove(int); //按位删除
bool clear(); //将顺序表置0
int find(int,int); //按位查找
int get_length(); //求顺序表的长度
bool judge(); //判断顺序表是否为空
bool seek(int); //按值查找
protected:
int* m_list;
int m_length;
};
Sequence_List::Sequence_List(int length)
{
if (length)
{
m_length = length;
m_list = new int[length];
}
else
{
m_length = 1;
m_list = new int[1];
}
}
inline Sequence_List::~Sequence_List()
{
delete[]m_list;
}
inline bool Sequence_List::insert(int index, int element) //时间复杂度O(n),空间复杂度O(1)
{
if (index < 0 || index >= m_length)
return false;
else
{
m_list = new int[m_length + 1];
for (int i = index + 1; i < m_length; i++)
{
m_list[i] = m_list[i - 1];
}
m_list[index] = element;
m_length++;
return true;
}
}
inline bool Sequence_List::remove(int index) //时间复杂度O(n),空间复杂度O(1)
{
if (index < 0 || index >= m_length)
return false;
else
{
m_list = new int[m_length -1];
for (int i = index + 1; i < m_length; i++)
{
m_list[i-1] = m_list[i];
}
m_length--;
return true;
}
}
inline bool Sequence_List::clear()
{
m_length = 0;
}
inline int Sequence_List::find(int index, int element) //时间复杂度O(1),空间复杂度O(1)
{
if (index < 0 || index >= m_length)
return 0;
else
return m_list[index];
}
inline int Sequence_List::get_length()
{
return m_length;
}
inline bool Sequence_List::judge()
{
if (m_length==0)
return true;
else
return false;
}
inline bool Sequence_List::seek(int element) //时间复杂度O(n),空间复杂度O(1)
{
for (int i = 0; i < m_length; i++)
{
if (m_list[i] == element)
return true;
else
return false;
}
}
#endif