Topic describes

Use a stack to realize a queue, complete the queue push and pop operations, queue elements are int type

The stack and queue are both arrays in terms of data structure, but with different characteristics. For the stack, the elements in the station are first in, last out (FILO), while the elements in the queue are first in, first out (FIFO).

Begin to implement

It’s easy to know that the underlying data structures are all arrays, and there are many functions in PHP that manipulate arrays


      
class quequ {
    public function queue(a){
        $stack = [];

        // Get 10 random numbers and push them into the stack
        for ($i=0; $i < 10; $i++) {
            $random  = rand(0.100);      / / random number
            $stack[] = $random;          // equivalent to array_push($stack, $random);
        }

        print_r($stack);                 // Output an array

        while (!empty($stack)) {
            $pop = array_shift($stack);  // First in, first out, eject the head of queue
            echo $pop .PHP_EOL;
        }
    }
}
$quequ = new quequ();
$quequ->queue();
Copy the code