C++基本链表容器的实现

  • list基本链表容器的实现:

在这里插入图片描述

代码:

#include<iostream>
using namespace std;

template<typename T>
class list
{
private:
	class node//节点
	{
	public:
		node(const T &data, node * p, node* n): m_data(data),m_pre(p), m_next(n){}//构造函数
		T m_data;
		node* m_pre;//前驱
		node* m_next;//后继
	};
	node* m_head;//链表头节点
	node* m_tail;//链表未节点
public:
	//缺省构造
	list():m_head(nullptr), m_tail(nullptr){}

	//复制构造
	list(const list& that) {
		for (node* p = that.m_head; p; p = p->m_next)
			push_back(p->m_data);
	}

	//析构函数
	~list() {
		clear();
	}
	
	//判断链表是否为空
	bool empty() {
		return m_head == nullptr && m_tail == nullptr;
		//头节点等于尾节点并且为空就说明链表为空
	}

	//链表清空
	void clear() {
		while (!empty())
			pop_prent();//循环调用输出头结点或者输出未结点的函数都可以
	}

	//添加头节点
	void push_prent(const T & data) {
		m_head = new node(data, nullptr, m_head);
		if (m_head->m_next)
			m_head->m_next->m_pre = m_head;
		else
			m_tail = m_head;
	}

	//删除头节点
	void pop_prent() {
		if (empty())
			return;
		node* ponde = m_head->m_next;
		delete m_head;
		if (ponde)
			ponde->m_pre = nullptr;
		else
			m_tail = nullptr;
		m_head = ponde;
	}

	//添加未节点
	void push_back(const T& data) {
		m_tail = new node(data, m_tail, nullptr);
		if (m_tail->m_pre)
			m_tail->m_pre->m_next = m_tail;
		else
			m_tail = m_head;
	}

	//删除尾节点
	void pop_back() {
		if (empty())
			return;
		node* ponde = m_tail->m_pre;
		delete m_tail;
		if (ponde)
			ponde->m_next = nullptr;
		else
			m_head = nullptr;
		m_tail = ponde;
	}

	//获取链表头元素
	T& get_prent() {
		if (empty())
			throw underflow_error("链表为空。");//抛出异常
		return m_head->m_data;
	}
	const T& get_prent() const {
		return const_cast<list*>(this)->get_prent();//去除const属性,调用上面的函数。
	}

	//获取链表未元素
	T& get_back() {
		if(empty())
			throw underflow_error("链表为空。");//抛出异常
		return m_tail->m_data;
	}
	const T& get_back()const {
		return const_cast<list*>(this)->get_back();
	}

	//获取链表大小
	size_t get_size() {
		size_t i = 0;
		for (node* p = m_head; p; p = p->m_next)
			++i;
		return i;
	}
	//重载输出<<运算符
	friend ostream& operator<<(ostream& os, list& ls);
};

ostream& operator<<(ostream& os, list<int>& ls)
{
	for (list<int>::node* p = ls.m_head; p; p = p->m_next)
		os << p->m_data << "  ";
	return os;
}

//代码模拟容器部分
//============================================================
//代码模拟用户部分


int main()
{
	list<int> ls;
	for (int i = 0; i < 5; i++)
		ls.push_prent(10 + i);
	
	for (int i = 0; i < 5; i++)
		ls.push_back(100 + i);
	cout << ls << endl;

	ls.pop_back();
	ls.pop_prent();
	cout << ls << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白学编程*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值