一.顺序表的概念
顺序表是在计算机内存中以数组的形式保存的线性表,线性表的顺序存储是指用一组地址连续的存储单元依次存储线性表中的各个元素、使得线性表中在逻辑结构上相邻的数据元素存储在相邻的物理存储单元中,即通过数据元素物理存储的相邻关系来反映数据元素之间逻辑上的相邻关系,采用顺序存储结构的线性表通常称为顺序表。顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中。
二.代码实现
#include<iostream>
using namespace std;
#define eleType int
struct SequentialList
{
eleType *elements;
int size;
int capacity;
};
void initializeList(SequentialList *list,int capacity)
{
list->elements=new eleType[capacity];
list->size=0;
list->capacity=capacity;
}
//初始化
void destroyList(SequentialList *list)
{
delete [] list->elements;
}
//删除表
int size(SequentialList *list)
{
return list->size;
}
//大小
bool isEmpty(SequentialList *list)
{
return list->size==0;
}
//是否为空
void insert(SequentialList *list,int index, eleType element)
{
if(index<0||index>list->size)
{
throw std::invalid_argument("Invalid index");
}
if(list->size==list->capacity)
{
int newCapacity=list->capacity*2;
eleType *newElements=new eleType[newCapacity];
for(int i=0;i<list->size;++i)
{
newElements[i]=list->elements[i];
}
delete [] list->elements;
list->elements=newElements;
list->capacity=newCapacity;
}
for(int i=list->size;i>index;--i)
{
list->elements[i]=list->elements[i-1];
}
list->elements[index]=element;
list->size++;
}
//插入
void deleteElement(SequentialList *list,int index)
{
if(index<0||index>=list->size)
{
throw std::invalid_argument("Invalid index");
}
for(int i=index;i<list->size-1;++i)
{
list->elements[i]=list->elements[i+1];
}
list->size--;
}
//删
int findElement(SequentialList *list,eleType element)
{
for(int i=0;i<list->size;i++)
{
if(list->elements[i]==element)
{
return i;
}
}
return -1;
}
//找
eleType getElement(SequentialList *list,int index)
{
if(index<0||index>=list->size)
{
throw std::invalid_argument("Invalid index");
}
return list->elements[index];
}
//查
void updateElement(SequentialList *list,int index,eleType value)
{
if(index<0||index>=list->size)
{
throw std::invalid_argument("Invalid index");
}
list->elements[index]=value;
}
//改
int main()
{
SequentialList myList;
initializeList(&myList,10);
for(int i=0;i<10;++i)
{
insert(&myList,i,i*10);
}
cout << "Size: " << size(&myList)<<endl;
cout<<"Is empty: "<<isEmpty(&myList)<<endl;
for(int i=0;i<size(&myList);i++)
{
cout<<getElement(&myList,i)<<" ";
}
cout<<endl;
deleteElement(&myList,5);
updateElement(&myList,1,1314);
for(int i=0;i<size(&myList);i++)
{
cout<<getElement(&myList,i)<<" ";
}
cout<<endl;
int index=findElement(&myList,20);
updateElement(&myList,index,520);
for(int i=0;i<size(&myList);i++)
{
cout<<getElement(&myList,i)<<" ";
}
destroyList(&myList);
return 0;
}