线性表与顺序表的区别:
线性表包括:顺序表、链表
线性表是逻辑概念,指数据是一维存储的结构。同一级的有树结构、图结构、集合。
顺序表是物理概念(空间概念),同一级的有链式结构。
C++实现:
/*顺序表用数组实现的操作的特点
1.通过元素的存储顺序反映线性表中
数据元素之间的逻辑关系;
2.可随机存取顺序表的元素;
3.顺序表的插入、删除操作要通过移动元素实现,效率较低;
4.元素较少时存储空间的利用率较低。*/
//线性表定义
#include<iostream>
#include<stdlib.h>
template <class Type>
class SeqList{
Type *data;
int MaxSize;
int last;
public:
SeqList(int MaxSize = 10);
~SeqList(){ delete[]data; }
int Length()const{ return last + 1; }
int Find(Type & x) const;
int Insert(Type & x,int i);
int Remove(Type & x);
int Next(Type & x);
int Prior(Type & x);
int IsEmpty(){ return last == -1; }
int IsFull(){ return last == MaxSize - 1; }
Type Get(int i){
return i < 0 || i > last ? NULL : data[i];
}
};
//下面是构造方法
template <class Type>
SeqList<Type>::SeqList(int size){
if (size > 0){
MaxSize = size;
last = -1;
data = new Type[MaxSize];
if (data == NULL){
MaxSize = 0;
last = -1;
return;
}
}
}
//Find函数
template<class Type>
int SeqList<Type>::Find(Type & x)const{
int i = 0;
while (i <= last && data[i] != x){
i++;
}
if (i > last){
return -1;
}
else return i;
}
//插入函数
template <class Type>
int SeqList<Type>::Insert(Type & x, int i){
if (i<0 || i>last + 1 || last = MaxSize - 1){
return 0;
}
for (int j = last; j >= i; j--){
data[j + 1] = data[j];
}
data[i] = x;
last += 1;
return 1;
}
//删除函数
template <class Type>
int SeqList<Type>::Remove(Type & x){
if (Find(x) != -1){
for (int j = Find(x); j < last; j++){
data[j] = data[j+1]
}
last--;
return 1;
}
else{
return 0;
}
}
//Next函数
template <class Type>
int SeqList<Type>::Next(Type & x){
int i = Find(x);
if (i > 0 && i < last){
return data[i + 1];
}
else{
return i+1;
}
}
//Prior函数
template <class Type>
int SeqList<Type>::Prior(Type & x){
int i = Find(x);
if (i > 0 && i < last){
return i - 1;
}
本文详细介绍了线性表与顺序表的概念区别,并通过C++实现顺序表,展示了顺序表的基本操作,如查找、插入、删除等。

1119

被折叠的 条评论
为什么被折叠?



