c++ stack栈 - queue对列 - list双向链表

2024-01-12  本文已影响0人  简书网abc
#include <future>
#include <iostream>
#include <stack>

using namespace std;

// 栈 不提供迭代器和遍历, 先进后出
void test01() {
    stack<int> s;
    s.push(10); // 进栈容器
    s.push(20);
    s.push(30);

    if( !s.empty() ) {
        cout << "栈的大小: " << s.size() << endl;
        while (!s.empty()) {
            cout << s.top() << " "; // 取出栈顶元素.
            s.pop();                // 删除栈顶元素.
        }
        cout << endl;
    }
    cout << "test01 end ... stack 栈操作 " << endl;
}

// 队列 不提供迭代器和遍历 先进先出
#include <queue>
void test02() {
    queue<int> q;
    q.push(10); // 进对列容器
    q.push(20);
    q.push(30);

    if( !q.empty() ) {
        cout << "队列的大小: " << q.size() << endl;
        while (!q.empty()) {
            cout << q.front() << " "; // 从对列头部取出数据,火车头.
            q.pop();                // 删除对列头部数据.
        }
        cout << endl;
    }
    cout << "test01 end ... queue 对列操作 " << endl;
}


#include <list>
void printListInt(list<int> &li) {
    list<int>::iterator it = li.begin();
    for (;  it != li.end() ; it++) {
        cout << *it << " ";
    }
    cout << endl;
}

// 双向链表 list
void test03() {
    list<int> li;
    li.push_back(10);
    li.push_back(20);
    li.push_back(30);
    li.push_back(40);
    li.push_back(50);
    printListInt(li);

    // list容器是双向迭代器,不支持+2, 支持++
    list<int>::iterator it = li.begin();
    it++;
    it++;
    li.insert(it, 3, 99);
    printListInt(li);

    // 链表的排序,标准stl-sort不支持
    li.sort();
    printListInt(li);
    li.reverse();           // 链表反转
    printListInt(li);

    cout << "test03 end ... list 双向链表操作 " << endl;
}

int main() {
    test01();
    test02();
    test03();
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读