数据结构:双链表list

list 是 C++ 标准库中的双向链表容器。

list初始化示例:

cpp 复制代码
#include <list>

int n = 7;


std::list<int> lst; // 初始化一个空的双向链表 lst


std::list<int> lst(n); // 初始化一个大小为 n 的链表 lst,链表中的值默认都为 0


std::list<int> lst{1, 3, 5}; // 初始化一个包含元素 1, 3, 5 的链表 lst


std::list<int> lst(n, 2); // 初始化一个大小为 n 的链表 lst,其中值都为 2

list常用操作示例:

cpp 复制代码
#include <iostream>
#include <list>
using namespace std;

int main() {

    list<int> lst{1, 2, 3, 4, 5};    // 初始化链表


    cout << lst.empty() << endl;    // 检查链表是否为空,输出:false


    cout << lst.size() << endl;    // 获取链表的大小,输出:5


    lst.push_front(0);    // 在链表头部插入元素 0

    lst.push_back(6);    // 在链表尾部插入元素 6


    cout << lst.front() << " " << lst.back() << endl;    // 获取链表头部和尾部元素,输出:0 6

    lst.pop_front();    // 删除链表头部元素

    lst.pop_back();    // 删除链表尾部元素


    auto it = lst.begin();    // 在链表中插入元素

    advance(it, 2);    // 移动到第三个位置

    lst.insert(it, 99);    // 在第三个位置插入 99


    it = lst.begin();    // 删除链表中某个元素

    advance(it, 1);    // 移动到第二个位置

    lst.erase(it);    // 删除第二个位置的元素

    // 遍历链表
    // 输出:1 99 3 4 5
    for (int val : lst) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

一般情况下,我们在头部增删元素会使用双链表,因为他在头部增删元素的效率比vector高。但我们通过索引访问元素时一般会使用vector。

相关推荐
豆沙沙包?31 分钟前
C++~~~stack容器、queue容器、list容器(p45-P56)
c++·windows·list
LuminousCPP5 小时前
数据结构‑二叉树(二):二叉堆从零实现|Heap结构设计 + 建堆优化 + 堆排序深度解析
c语言·数据结构·笔记·二叉树
6 小时前
数据结构第一课:复杂度解析
数据结构
欧叶冲冲冲8 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
_Narcissus_9 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.9 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
疯狂打码的少年11 小时前
【数据结构】八大排序算法对比总结(时间/空间/稳定性)
数据结构·笔记·算法
Awh-15 小时前
数据结构 第六章:哈希存储
数据结构·算法·哈希算法
TAN-90°-16 小时前
Deep Learning for Computer Vision——Recurrent Neural Networks
数据结构·人工智能·rnn·深度学习·神经网络·机器学习·计算机视觉
淡海水16 小时前
03-05-线性-Array-List-LinkedList与Span-所有权与成本模型选型
c#·list·编译·array·clr·机器码