C++学习笔记 —— STL之链表、队列、栈

文章目录

链表

链表list插入和删除永远是常数时间,采取动态分配不会浪费资源,
list是一个双向循环链表
非连续空间
头节点不保存数据

#include <iostream>
#include <list>
using namespace std;

using namespace std;

void printList(list<int> list)
{
    for (auto it = list.begin(); it != list.end(); it++)
    {
        cout << *it << ", ";
    }
    cout << endl;
}
int main()
{
    //初始化
    list<int> l(10, 5);
    list<int> l2(l.begin(), l.end());
    printList(l); //5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
    printList(l2);
    //l[2]; list不支持随机访问,也就是不能用下标访问
    
    
    //头部和尾部插入推入元素
    l.push_front(4);
    l.push_back(6);
    printList(l); //4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 
    l.front();//获取头部
    l.back();//获取尾部
    l.pop_front(); // 弹出头部
    l.pop_back(); //弹出尾部
    
    //插入
    l.insert(l.begin(),3); // 出入某个位置,插入元素。 当如果要在第五个位置插入的时候,需要迭代器指向第五个位置
    printList(l);//3, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
    //删除
    l.remove(5); //3, 删除所有为5的元素

    list<int> l3;
    l3.push_back(10);
    l3.push_back(20);
    l3.push_back(30);
    l3.push_back(40);
    printList(l3);//10, 20, 30, 40, 
    //反转
    l3.reverse();
    printList(l3);//40, 30, 20, 10, 
    //排序
    //sort 方法不可使用,不支持随机访问的迭代器,不能用sort方法
    l3.sort(); // 所以该容器自带排序方法 //也可以加参数为自定义排序方法
    printList(l3); //10, 20, 30, 40, 

}

队列和栈

#include <iostream>
#include <stack>
#include <queue>
using namespace std;


int main()
{
    // stack 先进后出,允许栈顶新增,栈顶移除,取得栈顶元素,不允许有遍历行为,也就是没有其他操作。
    stack<int> s;
    //压入数据
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    while (s.size() != 0) {
        cout << s.top() << endl;  //查看栈顶元素数值
        s.pop(); //弹出数据
    }
    //不提供遍历没有迭代器,只有队头元素才能被外界取用,队尾进入元素
    cout<< " queue: " << endl;
    queue<int> q;
    q.push(10);
    q.push(20);
    q.push(30);
    q.push(40);
    while (!q.empty()) //也可以用empty来判断
    {
        cout << q.front() << endl;  //查看队头元素
        cout << q.back() << endl;  //查看队尾元素
        q.pop();//弹出队头数据
    }
    
}
发布了103 篇原创文章 · 获赞 94 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/chongbin007/article/details/105646609