【C++操作手册】利用C++内置STL容器实现单链表各种功能定义

初始化单链表InitList(&L)

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

int main()
{
    
    
    list<int> L = {
    
    1, 2, 3, 4, 5};

    for (list<int>::iterator it = L.begin(); it != L.end(); it++)
    {
    
    
        cout << *it << '\t';
    }
}

在这里插入图片描述

求表长Length(L)

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

int main()
{
    
    
    list<int> L = {
    
    1, 2, 3, 4, 5};

    for (list<int>::iterator it = L.begin(); it != L.end(); it++)
    {
    
    
        cout << *it << '\t';
    }
    
    cout << endl;

    cout << "表长度:" << L.size() << endl;
}

在这里插入图片描述

按值查找LocateElem(L,e)

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

int main()
{
    
    
    list<int> L = {
    
    1, 2, 3, 4, 5};

    int key = 2;

    for (list<int>::iterator it = L.begin(); it != L.end(); it++)
    {
    
    
        if (*it == key)
        {
    
    
            cout << "找到元素" << endl;
            return 0;
        }
    }

    cout << "未找到元素" << endl;
}

在这里插入图片描述

按位查找GetElem(L,i)

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

int main()
{
    
    
    list<int> L = {
    
    1, 2, 3, 4, 5};

    int pos = 3;

    int i = 0;

    for (list<int>::iterator it = L.begin(); i <= pos && it != L.end(); it++, i++)
    {
    
    
        if (i == pos)
        {
    
    
            cout << *it << endl;
        }
    }
}

在这里插入图片描述

插入操作ListInsert(&L,i,e)

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

int main()
{
    
    
    list<int> L = {
    
    9, 2, 3, 4, 5};

    int value = 999;

    L.insert(L.begin(), value);

    for (list<int>::iterator it = L.begin(); it != L.end(); it++)
    {
    
    
        cout << *it << '\t';
    }
}

在这里插入图片描述

删除操作ListDelete(&L,i,e)

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

int main()
{
    
    
    list<int> L = {
    
    9, 2, 3, 4, 5};

    L.erase(L.begin());

    for (list<int>::iterator it = L.begin(); it != L.end(); it++)
    {
    
    
        cout << *it << '\t';
    }
}

在这里插入图片描述

输出操作PrintList(L)

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

int main()
{
    
    
    list<int> L = {
    
    9, 2, 3, 4, 5};

    for (list<int>::iterator it = L.begin(); it != L.end(); it++)
    {
    
    
        cout << *it << '\t';
    }
}

在这里插入图片描述

判空操作Empty(L)

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

int main()
{
    
    
    list<int> L = {
    
    9, 2, 3, 4, 5};

    cout << L.empty() << endl;

    L.clear();

    cout << L.empty() << endl;
}

在这里插入图片描述

销毁操作DestroyList(&L)

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

int main()
{
    
    
    list<int> L = {
    
    9, 2, 3, 4, 5};

    cout << &L << endl;
    
    delete &L;

    cout << &L << endl;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_47256162/article/details/124869947