zoukankan      html  css  js  c++  java
  • list双向链表容器(常用的方法总结)

      特别注意,由于list对象的结点并不要求在一段连续的内存中,所以,对于迭代器,只能通过++或者--的操作将迭代器移动到后继或者前驱结点元素处。而不能对迭代器进行+n或者-n的操作,
    这点与vector等不同的地方。

      

     1 /*关于C++STL中的list双向链表容器的学习。*/
     2 #include <list>
     3 #include <iostream>
     4 using namespace std;
     5 
     6 void print(list<int> l);
     7 void rprint(list<int> l);
     8 
     9 int main()
    10 {
    11     //创建list对象
    12     list<int> l;
    13     
    14     //插入元素的三种方式
    15     l.push_back(2);//向尾部插入元素,链表自动扩张
    16     l.push_front(1);//向首部插入元素,链表自动扩张
    17     
    18     //在链表中间插入新的元素
    19     list<int>::iterator it;
    20     it=l.begin();
    21     it++;//只能++或者--
    22     l.insert(it,4);
    23     cout<<"正向遍历:
    ";
    24     print(l); 
    25     cout<<"方向遍历:
    ";
    26     rprint(l);
    27     
    28     
    29     //元素的删除
    30     //值得特别注意的是如果想要删除该链表中所有键值为某值得元素时,使用remove()方法
    31     l.push_back(1);
    32     l.push_back(3); 
    33      l.push_back(5);
    34      cout<<"删除前:
    "; 
    35      print(l);
    36      l.remove(1);
    37      cout<<"删除后:
    ";
    38      print(l);
    39      
    40      //删除链表首元素和尾元素
    41      cout<<"删除前:
    ";    
    42      print(l);
    43     l.pop_front(); 
    44     l.pop_back();
    45     cout<<"删除后:
    ";
    46     print(l);
    47     //此外还可以使用erase()方法和clear()方法
    48     
    49     //元素的查找find()
    50     
    51     l.push_back(1);
    52     l.push_back(3); 
    53      l.push_back(5);
    54     //元素的排序
    55     cout<<"排序前:
    ";
    56     print(l);
    57     l.sort();//默认从小到大排序
    58     cout<<"排序后: 
    ";
    59     print(l);
    60     //自定义排序分为结构体和非结构体 
    61      
    62     //另外如果想要提出连续重复的元素则使用unique()方法 
    63     return 0;
    64 }
    65 
    66 void print(list<int> l)
    67 {
    68     //使用前向迭代器遍历链表
    69     list<int>::iterator it;
    70     for(it=l.begin(); it != l.end(); it++){
    71         cout<<(*it)<<endl; 
    72     } 
    73 }
    74 
    75 void rprint(list<int> l)
    76 {
    77     list<int>::reverse_iterator rit;
    78     for(rit = l.rbegin(); rit != l.rend(); rit++){
    79         cout<<(*rit)<<endl;
    80     }
    81 }
  • 相关阅读:
    21.Merge Two Sorted Lists 、23. Merge k Sorted Lists
    34. Find First and Last Position of Element in Sorted Array
    leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、301. Remove Invalid Parentheses
    31. Next Permutation
    17. Letter Combinations of a Phone Number
    android 常见分辨率(mdpi、hdpi 、xhdpi、xxhdpi )及屏幕适配注意事项
    oc 异常处理
    oc 类型判断
    oc Delegate
    oc 协议
  • 原文地址:https://www.cnblogs.com/wenzhixin/p/8529987.html
Copyright © 2011-2022 走看看