list的模拟实现

在 C++ 标准库中,list 是一个基于双向循环链表的容器,它以插入 / 删除操作高效、迭代器稳定等特性,成为 STL 容器家族的重要成员。本文将从数据结构设计、迭代器原理、内存管理等维度,详细解析 list 的模拟实现过程。

1. list的成员变量

1.1 节点结构(list_node)

双向链表的每个节点需要存储三部分信息:数据前驱指针 (指向前一个节点)、后继指针(指向后一个节点)。结构定义如下:

cpp 复制代码
template<class T>
struct list_node
{
    T _data;         // 存储数据的成员
    list_node<T>* _prev; // 指向前一个节点的指针
    list_node<T>* _next; // 指向后一个节点的指针

    // 构造函数:初始化数据和指针
    list_node(const T& data = T())
        :_data(data)
        ,_prev(nullptr)
        ,_next(nullptr)
    {}
};

_data: 存储任意类型的元素(由模板 T 决定)。
**_prev 和 _next:**通过指针形成双向链接,使链表能向前、向后遍历。

在这里使用struct而不是class是因为默认访问权限struct默认成员为public,而class是private,我们为了方便后续操作,直接设置为struct。

而在list类中我们的基础设计如下:

cpp 复制代码
template<class T>
class list
{
	typedef list_node<T> Node; // 节点类型别名
	// 构造、析构、拷贝控制、增删查改等接口...

private:
	Node* _head;   // 头结点(哨兵节点)
	size_t _size;  // 链表有效元素个数
};

标准库 list 采用双向循环链表,并引入一个头结点(哨兵节点)。头结点不存储有效数据,仅用于简化边界条件:

头结点的 _next 指向第一个有效节点;

头结点的 _prev 指向最后一个有效节点;

最后一个有效节点的 _next 指向头结点,形成循环。

2. list的迭代器

迭代器是 STL 容器的灵魂,它封装了对容器元素的访问逻辑。对于 list,迭代器需要支持解引用、前后移动、比较等操作。

2.1 迭代器的模板设计(list_iterator)

为了同时支持普通迭代器const 迭代器,我们采用模板参数 Ref(引用类型)和 Ptr(指针类型)来区分:

cpp 复制代码
template<class T, class Ref, class Ptr>
struct list_iterator
{
	typedef list_node<T> Node;       // 节点类型别名
	typedef list_iterator<T, Ref, Ptr> Self; // 迭代器自身类型别名
	Node* _node;                     // 指向当前节点的指针

	// 构造函数:用节点指针初始化迭代器
	list_iterator(Node* node) 
		:_node(node) 
	{}

	// 1. 解引用操作:获取节点数据
	Ref operator*() 
	{
		return _node->_data; 
	}
	Ptr operator->() 
	{
		return &_node->_data; 
	}

	// 2. 前置++:移动到下一个节点(返回自身引用)
	Self& operator++()
	{
		_node = _node->_next;
		return *this;
	}

	// 3. 前置--:移动到前一个节点(返回自身引用)
	Self& operator--()
	{
		_node = _node->_prev;
		return *this;
	}

	// 4. 后置++:移动到下一个节点(返回旧迭代器的拷贝)
	Self operator++(int)
	{
		Self tmp = *this;
		_node = _node->_next;
		return tmp;
	}

	// 5. 后置--:移动到前一个节点(返回旧迭代器的拷贝)
	Self operator--(int)
	{
		Self tmp = *this;
		_node = _node->_prev;
		return tmp;
	}

	// 6. 迭代器比较:判断是否指向同一个节点
	bool operator!=(const Self& s) const 
	{ 
		return _node != s._node; 
	}
	bool operator==(const Self& s) const 
	{ 
		return _node == s._node; 
	}
};

**Ref 和 Ptr 的作用:**当 T 是普通类型时,Ref 为 T& 、Ptr 为 T* ;当 T 是 const 类型时,Ref 为 const T& 、Ptr 为 const T* 。这样一份代码就能同时支持普通迭代器和 const 迭代器。

在list中:

cpp 复制代码
typedef list_iterator<T, T&, T*> iterator;
typedef list_iterator<T, const T&, const T*> const_iterator;

2.2 迭代器的 "不失效" 特性

  1. 与 vector 不同,list 的迭代器在插入和删除操作时不会失效(除非被删除的是自身)。原因是:

插入操作仅修改相邻节点的指针,不影响其他节点的迭代器(list内存不是连续的)。

  1. 删除操作返回 "下一个节点的迭代器",开发者可通过接收返回值保持迭代器有效性。

3. list的完整实现

3.1 类的基本结构与成员

cpp 复制代码
template<class T>
class list
{
    typedef list_node<T> Node; // 节点类型别名
public:
    // 普通迭代器和 const 迭代器
    typedef list_iterator<T, T&, T*> iterator;
    typedef list_iterator<T, const T&, const T*> const_iterator;

    // 构造、析构、拷贝控制、增删查改等接口...
private:
    Node* _head;   // 头结点(哨兵节点)
    size_t _size;  // 链表有效元素个数
};

3.2 初始化及构造函数

为了统一初始化逻辑,封装 empty_init 函数来初始化头结点:

cpp 复制代码
void empty_init()
{
    _head = new Node;       // 新建头结点
    _head->_next = _head;   // 头结点的 next 指向自身
    _head->_prev = _head;   // 头结点的 prev 指向自身
    _size = 0;              // 初始长度为 0
}

// 1. 默认构造
list() 
{ 
    empty_init(); 
}

// 2. 初始化列表构造(C++11 特性)
//关于这个我们目前来说了解即可,该构造可以让我们用多个元素直接构造
list(initializer_list<T> il)
{
    empty_init();
    for (auto& e : il)
    {
        push_back(e); // 逐个插入元素
    }
}

// 3. 拷贝构造(深拷贝)
list(const list<T>& lt)
{
    empty_init();
    for (auto& e : lt) // 遍历原链表,逐个插入元素
    {
        push_back(e);
    }
}

**拷贝构造的深拷贝:**必须遍历原链表并逐个插入元素,否则会导致多个链表共享同一份节点(浅拷贝)。

3.3 赋值运算符重载与析构函数

cpp 复制代码
void swap(list<T>& lt)
{
    std::swap(_head, lt._head); // 交换头结点指针
    std::swap(_size, lt._size); // 交换长度
}

// 赋值运算符重载(现代写法:利用拷贝构造 + 交换)
list<T>& operator=(list<T> lt)
{
    swap(lt); // 交换当前对象和临时对象的资源
    return *this;
}

// 析构函数
~list()
{
    clear();   // 清空所有有效节点
    delete _head; // 释放头结点
    _head = nullptr;
}

**赋值运算符的现代写法:**通过传值拷贝临时对象,再交换资源,既保证了异常安全,又简化了逻辑。

3.4 迭代器接口

提供 begin 和 end 接口,分别返回指向第一个有效节点和头结点的迭代器:

cpp 复制代码
iterator begin() { return _head->_next; }
iterator end() { return _head; }

const_iterator begin() const { return _head->_next; }
const_iterator end() const { return _head; }

begin() 指向第一个有效元素,end() 指向头结点(作为 "尾后迭代器"),符合 STL 容器的设计规范。

3.5 关键功能接口

(1)insert

insert 是双向链表的核心操作,它在指定迭代器 pos 前插入新节点:

cpp 复制代码
iterator insert(iterator pos, const T& x)
{
    Node* cur = pos._node;    // pos 指向的当前节点
    Node* prev = cur->_prev;  // 当前节点的前驱节点
    Node* newnode = new Node(x); // 新建节点

    // 建立双向链接
    cur->_prev = newnode;
    prev->_next = newnode;
    newnode->_prev = prev;
    newnode->_next = cur;

    ++_size; // 链表长度加 1
    return iterator(newnode); // 返回新节点的迭代器
}

基于 insert,可以封装 push_back(尾插)和 push_front(头插):

cpp 复制代码
// 在尾后迭代器前插入
void push_back(const T& x) 
{ 
	insert(end(), x); 
}   
// 在第一个元素前插入
void push_front(const T& x) 
{ 
	insert(begin(), x); 
} 

(2)erase

erase 负责删除 pos 指向的节点,并返回下一个节点的迭代器(保证迭代器不失效):

cpp 复制代码
iterator erase(iterator pos)
{
    assert(pos != end()); // 不能删除头结点(尾后迭代器)

    Node* prev = pos._node->_prev; // 待删节点的前驱
    Node* next = pos._node->_next; // 待删节点的后继

    // 跳过待删节点,建立新链接
    prev->_next = next;
    next->_prev = prev;
    delete pos._node; // 释放待删节点的内存
    --_size;          // 链表长度减 1

    return iterator(next); // 返回下一个节点的迭代器
}

基于 erase,可以封装 pop_back(尾删)和 pop_front(头删):

cpp 复制代码
// 删除第一个元素
void pop_front() 
{ 
	erase(begin()); 
} 
// 删除最后一个元素(先移动到最后一个有效节点)
void pop_back() 
{ 
	erase(--end()); 
} 

3.6 辅助接口实现

cpp 复制代码
//为了避免内存泄漏,需要提供 clear 方法清空链表,并在析构函数中释放所有资源
void clear()
{
	auto it = begin();
	while (it != end())
	{
		it = erase(it); // 逐个删除节点,利用 erase 返回的迭代器更新 it
	}
}
// 返回链表长度
size_t size() const 
{ 
	return _size; 
}
// 判断是否为空
bool empty() const 
{ 
	return _size == 0; 
} 

//打印容器
template <class Container>
void print_container(const Container& con)
{
	for (auto& e : con)
	{
		cout << e << " ";
	}
	cout << endl;
}

4. 源码

list.h

cpp 复制代码
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

namespace nep
{
	template<class T>
	struct list_node
	{
		T _data;
		list_node<T>* _prev;
		list_node<T>* _next;

		list_node(const T& data = T())
			:_data(data)
			,_prev(nullptr)
			,_next(nullptr)
		{}
	};

	//Ref 传的引用 Ptr 传的指针
	template<class T, class Ref, class Ptr>
	struct list_iterator
	{
		typedef list_node<T> Node;
		typedef list_iterator<T, Ref, Ptr> Self;
		Node* _node;

		list_iterator(Node* node)
			:_node(node)
		{}

		Ref operator*()
		{
			return _node->_data;
		}

		Ptr operator->()
		{
			return &_node->_data;
		}

		//前置
		Self& operator++()
		{
			_node = _node->_next;
			return *this;
		}

		Self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}

		//后置
		Self operator++(int)
		{
			Self tmp = *this;
			_node = _node->_next;
			return tmp;
		}

		Self operator--(int)
		{
			Self tmp = *this;
			_node = _node->_prev;
			return tmp;
		}

		bool operator!=(const Self& s) const
		{
			return _node != s._node;
		}

		bool operator==(const Self& s) const
		{
			return _node == s._node;
		}
	};

	template<class T>
	class list
	{
		typedef list_node<T> Node;
	public:
		typedef list_iterator<T, T&, T*> iterator;
		typedef list_iterator<T, const T&, const T*> const_iterator;

		iterator begin()
		{
			return _head->_next;
		}

		iterator end()
		{
			return _head;
		}

		const_iterator begin() const
		{
			return _head->_next;
		}

		const_iterator end() const
		{
			return _head;
		}

		void empty_init()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			_size = 0;
		}

		//默认构造
		list()
		{
			empty_init();
		}

		list(initializer_list<T> il)
		{
			empty_init();
			for (auto& e : il)
			{
				push_back(e);
			}
		}

		//拷贝构造
		list(const list<T>& lt)
		{
			empty_init();

			for (auto& e : lt)
			{
				push_back(e);
			}
		}

		//赋值运算符重载
		list<T>& operator=(list<T> lt)
		{
			swap(lt);
			return *this;
		}

		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}

		void clear()
		{
			auto it = begin();
			while (it != end())
			{
				it = erase(it);
			}
		}

		void swap(list<T>& lt)
		{
			std::swap(_head, lt._head);
			std::swap(_size, lt._size);
		}

		void push_back(const T& x)
		{
			insert(end(), x);
		}

		void push_front(const T& x)
		{
			insert(begin(), x);
		}

		iterator insert(iterator pos, const T& x)
		{
			Node* cur = pos._node;
			Node* prev = cur->_prev;
			Node* newnode = new Node(x);

			cur->_prev = newnode;
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = cur;

			++_size;
			return iterator(newnode);
		}

		void pop_front()
		{
			erase(begin());
		}

		void pop_back()
		{
			erase(--end());
		}

		iterator erase(iterator pos)
		{
			assert(pos != end());

			Node* prev = pos._node->_prev;
			Node* next = pos._node->_next;

			prev->_next = next;
			next->_prev = prev;
			delete pos._node;
			--_size;
			return iterator(next);
		}

		size_t size() const
		{
			return _size;
		}

		bool empty() const
		{
			return _size == 0;
		}

	private:
		Node* _head; //头结点
		size_t _size;
	};

	//测试类
	struct AA
	{
		int _a1 = 1;
		int _a2 = 1;
	};

	template <class Container>
	void print_container(const Container& con)
	{
		/*typename Container::const_iterator it = con.begin();
		while (it != con.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;*/

		for (auto& e : con)
		{
			cout << e << " ";
		}
		cout << endl;
	}
}

test.cpp

cpp 复制代码
#include"List.h"

namespace nep
{
	void test_list1()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);

		list<int>::iterator it = lt.begin();
		while (it != lt.end())
		{
			*it += 10;

			cout << *it << " ";
			++it;
		}
		cout << endl;

		for (auto e : lt)
		{
			cout << e << " ";
		}
		cout << endl;
		print_container(lt);

		list<AA> lta;
		lta.push_back(AA());
		lta.push_back(AA());
		lta.push_back(AA());
		lta.push_back(AA());
		list<AA>::iterator ita = lta.begin();
		while (ita != lta.end())
		{
			//cout << (*ita)._a1 << ":" << (*ita)._a2 << endl;
			// 特殊处理,本来应该是两个->才合理,为了可读性,省略了一个->
			cout << ita->_a1 << ":" << ita->_a2 << endl;
			cout << ita.operator->()->_a1 << ":" << ita.operator->()->_a2 << endl;

			++ita;
		}
		cout << endl;
	}

	void test_list2()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);

		print_container(lt);
		// insert以后迭代器不失效
		list<int>::iterator it = lt.begin();
		lt.insert(it, 10);
		*it += 100;

		print_container(lt);

		// erase以后迭代器失效
		// 删除所有的偶数
		it = lt.begin();
		while (it != lt.end())
		{
			if (*it % 2 == 0)
			{
				it = lt.erase(it);
			}
			else
			{
				++it;
			}
		}

		print_container(lt);
	}

	void test_list3()
	{
		list<int> lt1;
		lt1.push_back(1);
		lt1.push_back(2);
		lt1.push_back(3);
		lt1.push_back(4);

		list<int> lt2(lt1);

		print_container(lt1);
		print_container(lt2);

		list<int> lt3;
		lt3.push_back(10);
		lt3.push_back(20);
		lt3.push_back(30);
		lt3.push_back(40);

		lt1 = lt3;
		print_container(lt1);
		print_container(lt3);
	}

	void func(const list<int>& lt)
	{
		print_container(lt);
	}

	void test_list4()
	{
		// 直接构造
		list<int> lt0({ 1,2,3,4,5,6 });
		// 隐式类型转换
		list<int> lt1 = { 1,2,3,4,5,6,7,8 };
		const list<int>& lt3 = { 1,2,3,4,5,6,7,8 };

		func(lt0);
		func({ 1,2,3,4,5,6 });

		print_container(lt1);

		//auto il = { 10, 20, 30 };
	/*	initializer_list<int> il = { 10, 20, 30 };
		cout << typeid(il).name() << endl;
		cout << sizeof(il) << endl;*/
	}
}

int main()
{
	nep::test_list1();
	//nep::test_list2();
	//nep::test_list3();
	//nep::test_list4();
	return 0;
}

结语

好好学习,天天向上!有任何问题请指正,感谢观看!

相关推荐
superior tigre7 小时前
(huawei)最小栈
c++·华为·面试
渡我白衣7 小时前
C++:链接的两难 —— ODR中的强与弱符号机制
开发语言·c++·人工智能·深度学习·网络协议·算法·机器学习
小龙报7 小时前
《算法通关指南:数据结构和算法篇 --- 顺序表相关算法题》--- 1.移动零,2.颜色分类
c语言·开发语言·数据结构·c++·算法·学习方法·visual studio
再睡一夏就好7 小时前
【C++闯关笔记】使用红黑树简单模拟实现map与set
java·c语言·数据结构·c++·笔记·语法·1024程序员节
ceffans7 小时前
PDF文档中表格以及形状解析-后续处理(线段生成最小多边形)
c++·windows·算法·pdf
mifengxing8 小时前
力扣每日一题——接雨水
c语言·数据结构·算法·leetcode·动态规划·
小龙报9 小时前
《算法通关指南:数据结构和算法篇 --- 顺序表相关算法题》--- 询问学号,寄包柜,合并两个有序数组
c语言·开发语言·数据结构·c++·算法·学习方法·visual studio
序属秋秋秋9 小时前
《Linux系统编程之开发工具》【编译器 + 自动化构建器】
linux·运维·服务器·c语言·c++·自动化·编译器
夏玉林的学习之路10 小时前
正则表达式
数据库·c++·qt·mysql·正则表达式