list容器的用法
文章目录
1.出与入操作(类似队列)
#include<iostream>
#include<list>
using namespace std;
int main() {
list<int>l1;
l1.push_back(2);
l1.push_back(3);
l1.push_front(1);
l1.push_front(520);
l1.push_front(1314);
l1.pop_back();
l1.pop_front();
for (list<int>::iterator it = l1.begin(); it != l1.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
2.assign()与resize()//就不重复了
#include<iostream>
#include<list>
using namespace std;
int main() {
list<int>l1;
l1.push_back(2);
l1.push_back(3);
l1.push_front(1);
l1.push_front(520);
l1.push_front(1314);
l1.pop_back();
l1.pop_front();
l1.assign(20,530);
l1.resize(20);
for (list<int>::iterator it = l1.begin(); it != l1.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
3.打印链表的首元素与最后一个元素
#include<iostream>
#include<list>
using namespace std;
int main() {
list<int>l1;
l1.push_back(2);
l1.push_back(3);
l1.push_front(1);
l1.push_front(520);
l1.push_front(1314);
l1.pop_back();
l1.pop_front();
l1.resize(20);
l1.assign(20,530);
cout << l1.front() << endl;
cout << l1.back() << endl;
for (list<int>::iterator it = l1.begin(); it != l1.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
4.删除与反转操作
#include<iostream>
#include<list>
using namespace std;
int main() {
list<int>l1;
l1.push_back(2);
l1.push_back(3);
l1.push_front(1);
l1.push_front(520);
l1.push_front(1314);
l1.pop_back();
l1.pop_front();
//l1.resize(20);
//l1.assign(20,530);
cout << l1.front() << endl;
cout << l1.back() << endl;
//l1.remove(530);
l1.reverse();
l1.erase(l1.begin());
l1.remove(2);
//l1.erase(l1.begin());
for (list<int>::iterator it = l1.begin(); it != l1.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
5.swap()
#include<iostream>
#include<list>
using namespace std;
int main() {
list<int>l1;
list<int>l2;
l1.push_back(2);
l1.push_back(3);
l1.push_front(1);
l1.push_front(520);
l1.push_front(1314);
l1.pop_back();
l1.pop_front();
//l1.resize(20);
//l1.assign(20,530);
cout << l1.front() << endl;
cout << l1.back() << endl;
//l1.remove(530);
l1.reverse();
l1.erase(l1.begin());
l1.remove(2);
//l1.erase(l1.begin());
for (list<int>::iterator it = l1.begin(); it != l1.end(); it++) {
cout << *it << " ";
}
cout << endl;
l1.swap(l2);
for (list<int>::iterator it = l2.begin(); it != l2.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
6.最后链表不能用下表赋值法(at和[])并无定义
7.插入操作
#include<iostream>
#include<list>
using namespace std;
int main() {
list<int>l1;
list<int>l2;
l1.push_back(2);
l1.push_back(3);
l1.push_front(1);
l1.push_front(520);
l1.push_front(1314);
l1.pop_back();
l1.pop_front();
//l1.resize(20);
//l1.assign(20,530);
cout << l1.front() << endl;
cout << l1.back() << endl;
//l1.remove(530);
l1.reverse();
l1.erase(l1.begin());
l1.remove(2);
//l1.erase(l1.begin());
for (list<int>::iterator it = l1.begin(); it != l1.end(); it++) {
cout << *it << " ";
}
cout << endl;
l1.swap(l2);
l1.insert(l1.end(), 520);
for (list<int>::iterator it = l2.begin(); it != l2.end(); it++) {
cout << *it << " ";
}
cout << endl;
}