【C++编程】链表 list 容器基本操作

🔥 特点:list 任何位置执行插入和删除动作都非常快

list 每个节点包含数据域和指针域,不支持随机存取
list 链式存储,遍历速度没有数组 vector 快
STL 中的链表是一个双向循环链表

步骤零: 使用时需要包含头文件 #include <list>

void printList(list<int> &l) // 逐个元素打印
{
    for (list<int>::iterator i = l.begin(); i!=l.end(); i++)
    {
        cout << *i << endl;
    }
}

💜 list 构造与赋值

// 1. 默认构造
list<int> l1 = {0,1,2,3,4,5,6,7,8,9};
list<int> l11;
l11 = l1;  // 赋值 0 1 2 3 4 5 6 7 8 9
l11.assign(l1.begin(), l1.end());  // 赋值 0 1 2 3 4 5 6 7 8 9
l11.assign(10, 1);  // 赋值 1 1 1 1 1 1 1 1 1 1 

// 2. 通过区间构造
list<int> l2(l1.begin(), l1.end());   	

// 3. n个element
list<int> l3(10, 1); 	 
    
// 4. 拷贝构造			
list<int> l4(l1); 			

💜 list 插入和删除:push_back/frontpop_back/frontinserteraseclearremove

list<int> l1 = {0,1,2,3,4,5,6,7,8,9};
l1.push_back(10);  // 0 1 2 3 4 5 6 7 8 9 10  			- 尾插 10
l1.pop_back();  // 0 1 2 3 4 5 6 7 8 9 		  			- 尾删 10
l1.push_front(-1); // -1 0 1 2 3 4 5 6 7 8 9   			- 头插 -1
l1.pop_front(); // 0 1 2 3 4 5 6 7 8 9 		  			- 头删 -1

l1.insert(l1.begin(), -1);  // -1 0 1 2 3 4 5 6 7 8 9	- l1.begin() 处插入 -1
l1.erase(l1.begin());  // 0 1 2 3 4 5 6 7 8 9	  		- l1.begin() 处删除 -1

l1.clear(); // 清空

list<int> l2 = {0,1,2,3,4,4,4,5,6,7,8,9};
l2.remove(4);  // 0 1 2 3 5 6 7 8 9  					- 移除 4 (所有)

💜 list 大小获取:emptysize

list<int> l1 = {0,1,2,3,4,5,6,7,8,9};
cout << l1.empty() << endl;     // 0
cout << l1.size() << endl;      // 10

💜 list 元素互换:swap

list<int> l1 = {0,1,2,3,4,5,6,7,8,9};
list<int> l2 = {-0,-1,-2,-3,-4,-5,-6,-7,-8,-9};
l1.swap(l2);
// l1: -0,-1,-2,-3,-4,-5,-6,-7,-8,-9
// l2: 0,1,2,3,4,5,6,7,8,9

💜 list 反转和排序:reversesort

// 需要头文件 #include <algorithm>
list <int>l1 = {0,1,3,2,4,8,5,6,7,9};
l1.reverse();               // 9 7 6 5 4 2 3 1 0
l1.sort();                  // 0 1 2 3 4 5 6 7 8 9
l1.sort(greater<int>());    // 9 8 7 6 5 4 3 2 1 0

【博客参考链接】
【黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值