//list双向链表中任意位置的元素查找, //插入和删除都具有高效的常数阶算法时间复杂度O(1). #include<iostream> #include<cstdio> #include<list> using namespace std; struct student { char *name; int age; char *city; }; void print(list<student>&l) { list<student>::iterator i; for(i = l.begin(); i != l.end(); i++) { cout<<(*i).name<<" "; cout<<(*i).age<<" "; cout<<(*i).city<<" "<<endl; } } int main() { student s[] = { {"张三", 18, "浙江"}, //插入元素 {"李四", 19, "北京"}, {"王二", 18, "上海"} }; list<student>l; l.push_back(s[0]); l.push_back(s[1]); l.push_back(s[2]); student x = {"六四", 19, "新疆"}; l.push_front(x); //插入到首位置,复杂度为O(1) l.insert(l.begin(), x); //插入到任意位置,复杂度为O(1) //l.pop_front(); //删除首位置元素 //l.pop_back(); //删除韦位置元素 l.erase(l.begin()); //l.remove(2); //删除所有值为2的元素,结构体未知方法 //l.clear(); //删除所有元素 //l.erase(l.begin(), l.end()); //删除区间的元素,方法为完全掌握 print(l); list<student>::reverse_iterator ri; for(ri = l.rbegin(); ri != l.rend(); ri++) cout<<(*ri).name; getchar(); return 0; }
链表归并
//链表归并的查考代码如下例所示: #include<iostream> #include<cstdio> #include<list> using namespace std; struct student { char *name; int age; char *city; }; void print(list<int> l) { list<int>::iterator i; for(i = l.begin(); i != l.end(); i++) cout<<*i<<" "; cout<<endl; } int main() { list<int>l1; for(int j = 10; j >= 0; j--) l1.push_back(j); list<int>l2; list<int>::iterator ii; ii = l2.begin()++; l2.splice(l2.begin(), l1); //将l1的全部元素归并到L2,L1清空 l1.splice(l1.begin(), l2, ii); //将L2的ii位置的元素归并到L1,L2原元素删除 swap(l1, l2); //交换L1,L2 l1.sort(); //排序 l1.push_back(8); l1.push_back(8); l1.push_back(35); l1.push_back(30); l1.unique(); //删除连续重复元素 l2.merge(l1); //L1归并到L2,需要两个链表均排序,最后的结果也为排序的结果 print(l1); print(l2); getchar(); return 0; }