顺序表实现

本文详细介绍了线性表与顺序表的概念区别,并通过C++实现顺序表,展示了顺序表的基本操作,如查找、插入、删除等。

线性表与顺序表的区别:

线性表包括:顺序表、链表

线性表是逻辑概念,指数据是一维存储的结构。同一级的有树结构、图结构、集合。

顺序表是物理概念(空间概念),同一级的有链式结构。

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;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值