Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ reverse function

C++ reverse function

C++ Container Class The C++ container class


reverse is used in list toreverses the linked listfunction; it is a list-specific efficient operation.

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

In list,reverse has a time complexity of O(n), and does not move elements; it only adjusts pointers.

Word meaning: reverse means "reverse," i.e., to reverse the order of the linked list.


Basic syntax and parameters

Syntax format



void reverse();

Function description


Example

Example 1: Reverse the linked list

Example

#include

#include

int

main

(

)

{

    std

::

list

<

int

numbers

=

{

1

,

2

,

3

,

4

,

5

}

;

    std

::

cout

<<

"Before reverse: "

;

   

for

(

int

n

:

numbers

)

std

::

cout

<<

n

<<

" "

;

    std

::

cout

<<

std

::

endl

;

    numbers.

reverse

(

)

;

    std

::

cout

<<

"After reverse: "

;

   

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

#include

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 The C++ container class