C++ <list> reverse function

C++ container class <list>


reverseis used in the list forReverse linked listThe function is an efficient operation unique to linked lists.

reverseIt is a member function of the container class, used to reverse the order of elements in a linked list.

In the list,reverseIts time complexity is O(n), and it does not cause element movement, only adjusting pointers.

Word Definitions: reverseIt means "reverse", that is, reversing the order of the linked list.


Basic syntax and parameters

Syntax format

void reverse();

Function description

  • Return Value: void(No return value).
  • Effect: Reverse the order of elements in a linked list.

Example

Example 1: Reverse Linked List

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {1, 2, 3, 4, 5};

    std::cout << "Before reversing: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    numbers.reverse();

    std::cout << "After reversing: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected output:

反转前: 1 2 3 4 5
反转后: 5 4 3 2 1

Example 2: Reverse Again

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> data = {10, 20, 30};

    data.reverse();
    std::cout << First reversal:;
    for(int n : data) std::cout << n << " ";
    std::cout << std::endl;

    data.reverse();
    std::cout << Second reversal:;
    for(int n : data) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected output:

第一次反转: 30 20 10
第二次反转: 10 20 30

C++ container class <list>

other extensions