Queues: A Tale of Two Stacks

  • + 0 comments

    Solution in PHP

    <?php
    $_fp = fopen("php://stdin", "r");
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    
    $q = intval(trim(fgets(STDIN)));
    $array = [];
    for ($t_itr = 0; $t_itr < $q; $t_itr++) {
        $s = rtrim(fgets(STDIN), "\r\n");
        $arr = array_map('intval', preg_split('/ /', $s, -1, PREG_SPLIT_NO_EMPTY));
        if ($arr[0] == 1 && !empty($arr[1])) {
            array_unshift($array, $arr[1]);
        } elseif ($arr[0] == 2) {
            array_pop($array);
        } elseif ($arr[0] == 3) {
            echo $array[count($array)- 1] . PHP_EOL;
        }
    }
    fclose($_fp);
    ?>