功能描述:

    • 将容器中的元素反转,以及将容器中的数据进行排序。

    函数原型:

    • reverse(); //翻转链表
    • sort(); //链表排序

    代码演示:

    1. #include<iostream>
    2. #include<list>
    3. using namespace std;
    4. //list容器的反转和排序
    5. void printList(const list<int> &L) {
    6. for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
    7. cout << *it << " ";
    8. }
    9. cout << endl;
    10. }
    11. //降序排序
    12. bool mycompare(int a, int b) {
    13. return a > b;
    14. }
    15. //反转
    16. void test01() {
    17. list<int>L1;//默认构造
    18. L1.push_back(10);
    19. L1.push_back(20);
    20. L1.push_back(30);
    21. L1.push_back(40);
    22. cout << "反转前: ";
    23. printList(L1);
    24. //反转
    25. L1.reverse();
    26. cout << "反转前: ";
    27. printList(L1);
    28. }
    29. //排序
    30. void test02() {
    31. list<int>L1;//默认构造
    32. L1.push_back(30);
    33. L1.push_back(40);
    34. L1.push_back(10);
    35. L1.push_back(20);
    36. cout << "排序前: ";
    37. printList(L1);
    38. //反转
    39. L1.sort();
    40. cout << "排序后: ";
    41. printList(L1);
    42. //降序排序
    43. L1.sort(mycompare);
    44. cout << "降序排序后: ";
    45. printList(L1);
    46. }
    47. int main() {
    48. test01();
    49. test02();
    50. return 0;
    51. }

    运行结果:
    image.png