c++实现循环链表

这篇博客详细介绍了如何使用C++编程语言实现循环链表的数据结构,包括头文件`cyclelist.h`的定义,源文件`cyclelist.cpp`中的实现细节,以及用于测试的`main.cpp`代码示例。

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

cyclelist.h

#pragma once
#include <iostream>

using namespace std;

class Node
{
public:
	Node() {}
	Node(int e, Node* p = nullptr) : data(e), next(p) {}
	~Node() {}
public:
	int data;
	Node* next;
};


class CycleList
{
public:
	CycleList();
	~CycleList();

	//判断列表是否为空
	bool isEmpty();
	//头部添加元素
	void appendHead(int e);
	//尾部添加元素
	void appendTail(int e);
	//获取元素位置
	int getElemPos(int e);
	//获取指定位置的Node指针
	Node* getElement(int pos);
	//向指定位置插入元素
	void insertElem(int pos, int e);
	//删除首个与e相同的元素
	void deleteElem(int e);
	//移除pos位置上的元素
	void removeElem(int pos);
	//清空列表
	void clear();
	//打印列表
	void printList();
	int getLength() { return m_length; }

private:
	Node* head;
	Node* rear;
	int m_length;
};

cyclelist.cpp

#include "CycleList.h"

CycleList::CycleList()
	: m_length(0)
{
	head = new Node;
	head->next = head;
	head->data = 0;
	rear = nullptr;
}

CycleList::~CycleList()
{
	if (head)
	{
		Node* p = head->next;
		while (p != rear)
		{
			head->next = p->next;
			delete p;
			p = head->next;
		}
		delete head;
		head = nullptr;
		delete rear;
		rear = nullptr;
	}
}

bool CycleList::isEmpty()
{
	if (m_length > 0)
		return false;
	return true;
}

void CycleList::appendHead(int e)
{
	if (head == head->next)
	{//空表
		Node* node = new Node(e);
		head
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值