PHP - Ds Deque::rotate() 函数



PHP 的 Ds\Deque::rotate() 函数用于将当前双端队列旋转给定次数。如果“rotations”参数值为正,则双端队列将顺时针旋转(这意味着元素被移到末尾)。如果它是一个负值,则双端队列将逆时针旋转(或者元素将以相反的顺序旋转)。

通常,手动旋转双端队列 n 次是一个漫长的过程。相反,在 PHP 中使用 rotate() 函数有助于在更短的时间内旋转双端队列 n 次。

语法

以下是 PHP Ds\Deque::rotate() 函数的语法:

public Ds\Deque::rotate(int $rotations):void 

参数

此函数接受一个名为“rotations”的参数,如下所述:

  • rotations − 一个整数值,表示应旋转双端队列的次数。

返回值

此函数不返回值。

示例 1

以下是 PHP Ds\Deque::rotate() 函数的基本示例:

<?php
   $deque = new \Ds\Deque([10, 100, 1000, 10000]);
   echo "The original deque elements are: \n";
   print_r($deque);
   $rotations = 2;
   echo "Number of rotations: ".$rotations;
   echo "\nThe deque after rotation: \n";
   $deque->rotate($rotations);
   print_r($deque);
?>

输出

上述程序产生以下输出:

The original deque elements are:
Ds\Deque Object
(
    [0] => 10
    [1] => 100
    [2] => 1000
    [3] => 10000
)
Number of rotations: 2
The deque after rotation:
Ds\Deque Object
(
    [0] => 1000
    [1] => 10000
    [2] => 10
    [3] => 100
)

示例 2

以下是 PHP Ds\Deque::rotate() 函数的另一个示例。我们使用此函数来旋转此 (['a', 'b', 'c', 'd', 'e']) 双端队列:

<?php
   $deque = new \Ds\Deque(['a', 'b', 'c', 'd', 'e']);
   echo "The original deque elements are: \n";
   print_r($deque);
   $rotations = 4;
   echo "Number of rotations: ".$rotations;
   echo "\nThe deque after rotation: \n";
   $deque->rotate(4);
   print_r($deque);
?>

输出

执行上述程序后,将显示以下输出:

The original deque elements are:
Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)
Number of rotations: 4
The deque after rotation:
Ds\Deque Object
(
    [0] => e
    [1] => a
    [2] => b
    [3] => c
    [4] => d
)

示例 3

当我们将旋转值作为 -1 传递给此函数时,它将按如下方式逆时针反转双端队列中元素的顺序

<?php
   $deque = new \Ds\Deque(["a", "b", "c", "d"]);
   echo "The original deque: \n";
   print_r($deque);
   $rotations = -1;
   echo "Number of rotations: ".$rotations;
   $deque->rotate($rotations);
   echo "\nThe deque after reverse: \n";
   print_r($deque);
?>

输出

执行上述程序后,它将生成以下输出:

The original deque:
Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
Number of rotations: -1
The deque after reverse:
Ds\Deque Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)
广告