C++ 实现线性表的顺序存储(顺序表)

关于数据结构中的 线性表(队列、栈)的相关讲解,请看
C++ 实现数据结构中的线性表

1.线性表的顺序存储的结构代码

typedef int ElementType;
#define Maxsize 10
struct Sequence
{
ElementType data[Maxsize];//存储数据的数组
int  length;//线性表当前的长度
};

2.具体的方法实现,定义一个Sequence类

//head.h
typedef int Element_type;
#define Maxsize 10
#include<iostream>//必须加头文件
using namespace std;//必须加命名空间
class Sequence
{
private:
	struct sequence
	{
		Element_type data[Maxsize];
		int length;//此表中有数值的元素数量
	};
	sequence *x;//指向结构体(一个顺序表)的指针
public:
	Sequence();
	~Sequence(){delete x;}
	Sequence(const Sequence &se);
	Sequence &operator=(const Sequence &se);
	void Insert(Element_type n, int i);
	void Delete(int i);
	friend ostream& operator<<(std::ostream&os, Sequence& se);
};

具体函数

//method.cpp
#include"head.h"
Sequence::Sequence()
{
	x=new sequence;//创建一个顺序表,并用指针指向
	for (int n = 0; n < Maxsize; n++)
		x->data[n] = -1;//把数据初始化为-1
	x->length = 0;
}
Sequence::Sequence(const Sequence &se)
{
	x = new sequence;
	for (int n = 0; n < se.x->length; n++)
		this->x->data[n] = se.x->data[n];
	this->x->length = se.x->length;
}
Sequence &Sequence::operator=(const Sequence &se)
{
	x = new sequence;
	for (int n = 0; n < se.x->length; n++)
		this->x->data[n] = se.x->data[n];
	this->x->length = se.x->length;
	return *this;
}
void Sequence::Insert(Element_type n, int i)
{
	if (this->x->length == Maxsize)
		cout << "表满"<<endl;
	if (i > this->x->length+1||i<1)
		cout << "位置不合法"<<endl;
	if (i<=this->x->length)//如果不是在表尾插入
	{
		for (int j = this->x->length - 1; j >= i-1; j--)
			this->x->data[j + 1] = x->data[j];
	}
	//在表尾插入
	this->x->data[i - 1] = n;
	this->x->length++;
	
}
void Sequence::Delete(int i)//第i个位置,对应下标i-1
{
	if (i > this->x->length)
		cout << "此位置不存在"<<endl;
	if (i < this->x->length)
	{
		for (int n = i; n < this->x->length; n++)
			x->data[n - 1] = x->data[n];
	}
	this->x->length--;
}
ostream& operator<<(ostream& os,  Sequence& se)
{
	
	for (int n = 0; n < se.x->length; n++)
		os << se.x->data[n] << endl;
	return os;
}

主函数

//main.cpp
#include"head.h"
void main()
{
	Sequence se;
	for (int n = 1; n < 7; n++)
		se.Insert(n, n);
	se.Delete(6);
	cout << se;

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值