PHP uses two stacks to implement queue function

  • 2021-09-04 23:37:51
  • OfStack

This paper illustrates the method of PHP using two stacks to realize queue function. Share it for your reference, as follows:

Problem

Two stacks are used to implement a queue, and Push and Pop operations of the queue are completed. The elements in the queue are of type int.

Solutions

Two stacks. When leaving the stack, if the stack 2 is not empty, leave the stack 2. If Stack 2 is empty, the exit of Stack 1 is re-entered into Stack 2.

Implementation code


<?php
$arr1 = array();
$arr2 = array();
function mypush($node)
{
  array_push($arr1,$node);
}
function mypop()
{
  if(!empty($arr2)){
    return array_pop($arr2);
  }else{
    while(!empty($arr1)){
      array_push($arr2, array_pop($arr1));
    }
    return array_pop($arr2);
  }
}

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: