C++数据结构:1 线性表

类成员

创建一个数组类,类的成员属性有数组、数组的长度和数组的容量

class seqList
{
public:
	int length;
	int capacity;
	int *arr=new int[capacity];

	void Init(seqList& l);
	void Push();
	void Show();
	void Insert();
	void Pop();
	void Delete();
};

成员函数是实现线性表的各种功能

初始化

线性表的初始化需要定义其容量,并将数组长度初始化为0

void seqList::Init(seqList& l)
{
	l.length = 0;
	l.capacity = 100;
}

尾插

在数组末尾插入新的数据,插入完成后将线性表的长度+1
但若该线性表已满,即this->length==this->capacity则插入失败。我懒得写了,就不写了

void seqList::Push()
{
	cout << "piz input the ele" << endl;
	int x = 0;
	cin >> x;
	this->arr[this->length] = x;
	this->length++;
	cout << "push completed!" << endl;
	system("pause");
}

显示

本质就是遍历,然后打印

void seqList::Show()
{
	for (int i = 0; i < this->length; i++)
	{
		cout << this->arr[i] << " ";
	}
	cout << endl;
}

插入

插入的目的是可以选择插到哪里,比尾插更灵活
输入合理的位置pos后,将线性表长度+1,遍历pos之后的数据,将每个数据往后移一个,最后将新的数据放在pos上

void seqList::Insert()
{
	int pos = 0;
	int x = 0;
	cout << "plz input pos u want to insert" << endl;
	cin >> pos;
	cout << "plz input x u want to insert" << endl;
	cin >> x;

	if (pos > this->length || pos < 0)
	{
		cout << "no such pos! " << endl;
	}
	else
	{
		this->length++;
		for (int i = this->length; i > pos-1; i--)
		{
			cout << i;
			this->arr[i] = this->arr[i-1];
		}
		this->arr[pos-1] = x;
		
		cout << "insert completed!" << endl;
		system("pause");
		
	}
}

尾删

将线性表长度-1即可

void seqList::Pop()
{
	this->length--;
	cout << "pop completed!" << endl;
	system("pause");
}

删除

可指定值删除
输入存在的值后遍历数组直到查找到
当然也有找不到的情况,就是输入不存在的值,这种情况直接返回就好,我懒得写了
记得最后把长度-1

void seqList::Delete()
{
	int x = 0;
	cout << "plz input x u want to delete" << endl;
	cin >> x;
	for (int i = 0; i < this->length; i++)
	{
		if (this->arr[i] == x)
		{
			for (; i < this->length; i++)
			{
				this->arr[i] = this->arr[i + 1];
			}
		}
	}
	this->length--;
	cout << "delete completed!" << endl;
	system("pause");
}

实现

通过创建一个对象,通过该对象实现各种操作

seqList v;

可直接在main函数调用,也可通过switch选择

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值