list 函数
* 23-12-10 19:49
熟悉链表的库函数操作:创建链表,插入元素,删除元素,查找元素,为链表排序 遍历元素 掌握其使用
这里用模板实现
*/
#include <iostream>
#include <list> //链表头文件
#include <algorithm> //find函数头文件
using namespace std;
int main()
{
list<int> L;
list<int>::iterator it;
//插入元素 输出
int i=0,n; //插入数量
int num;
cout<<"输入要插入元素的个数:";
cin>>n;
cout<<"输入"<<n<<"个元素:"<<endl;
while (i<n)
{
cin>>num;
L.push_back(num); //重尾部插入元素 这样可以保证元素的顺序正确
i++;
}
//输出
for (it=L.begin(); it!=L.end(); it++)
{
cout<<*it<<" ";
}
cout<<endl;
//查找元素
int searh;
cout<<"输入要找的元素:";
cin>>searh;
it = find(L.begin(), L.end(), searh);
if (it!=L.end())
{
cout<<searh<<"查找成功"<<endl;
}
else
{
cout<<"查找失败"<<endl;
}
//排序
L.sort();
//输出
cout<<"排好序后的元素为:"<<endl;
for (it=L.begin(); it!=L.end(); it++)
{
cout<<*it<<" ";
}
cout<<endl;
//删除元素
int k = 0;
int de;
cout<<"输入要删除第几个元素:";
cin>>de;
while (k!=de)
{
it++;
k++;
}
L.erase(it); //删除元素 remove函数也行,相同元素一起删除
cout<<"删除后的元素为:"<<endl;
for (it=L.begin(); it!=L.end(); it++)
{
cout<<*it<<" ";
}
cout<<endl;
//插入元素
int inser,m,h=0;
cout<<"输入要插入的元素:";
cin>>inser;
cout<<"输入要插入的位置:";
cin>>m;
while (h!=m)
{
it++;
h++;
}
//插入元素
L.insert(it, inser); //在it位置插入num
cout<<"插入后的元素为:"<<endl;
for (it=L.begin(); it!=L.end(); it++)
{
cout<<*it<<" ";
}
cout<<endl;
system("pause");
return 0;
}
栋栋

浙公网安备 33010602011771号