链表的实现(c++)

本文详细介绍了一种使用C++实现链表的数组方法,包括插入、删除、获取元素等基本操作,以及如何检查链表是否为空和获取链表长度。通过具体的代码示例,展示了链表的基本操作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链表的实现(c++)

链表的数组实现

#include "stdafx.h"
#include <iostream>
using namespace std;

class Alist
{
private:
	int maxsize;
	int listsize;
	int curr;//当前指向的对象
	char* listarray;

public:
	Alist(int size)
	{
		maxsize = size;
		listsize = curr = 0;
		listarray = new char[maxsize];
	}

	~Alist() { delete[] listarray; }

	void clear()
	{
		delete[] listarray;
		listsize = curr = 0;
		listarray = new char[maxsize];
	}

	void insert(const char& it, int position)
	{
		for (int i = listsize; i > position - 1; i--)
			listarray[i] = listarray[i - 1];
		listarray[position - 1] = it;
		listsize++;
	}

	void append(const char& it)
	{
		listarray[listsize++] = it;
	}

	void move(int position)
	{
		if (position > listsize)
			cout << "Out of range!" << endl;
		char it = listarray[position - 1];
		for (int i = position - 1; i < listsize - 1; i++)
			listarray[i] = listarray[i + 1];
		listsize--;
	}

	void getValue(int position)
	{
		cout << "The " << position << " element is " << listarray[position - 1];
	}

	void length() const
	{
		cout << "The length of the list is " << listsize << endl;
	}

	void thelist()
	{
		for (int i = 0; i < listsize; i++)
			cout << listarray[i] << " ";
		cout << endl;
	}

	void ifempty()
	{
		if (listsize == 0)
			cout << "The list is empty." << endl;
		else
			cout << "The list is not empty." << endl;
	}

	void position(const char& it)
	{
		for (int i = 0; i < listsize; i++)
		{
			if (listarray[i] == it)
				cout << it << " is the " << i + 1 << " element" << endl;
		}
		cout << "a is the fisrt element" << endl;
	}

};


int main()
{
	Alist Alist1(10);
	Alist1.append('a');
	Alist1.append('b');
	Alist1.append('c');
	Alist1.append('d');
	Alist1.append('e');
	Alist1.thelist();
	Alist1.length();
	Alist1.ifempty();
	Alist1.getValue(3);
	Alist1.position('a');
	Alist1.insert('f', 4);
	Alist1.thelist();
	Alist1.move(3);
	Alist1.thelist();
	int a;
	cin >> a;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值