1. 程式人生 > >面試題30:包含 min 函式的棧

面試題30:包含 min 函式的棧

NowCoder

<?php
header("content-type:text/html;charset=utf-8");
/*
 * 定義棧的資料結構,請在該型別中實現一個能夠得到棧中所含最小元素的min函式(時間複雜度應為O(1))。 P165
 */

$myStack = new SplStack();
$myMin = new SplStack();
function mypush($node)
{
    global $myStack;
    global $myMin;
    $myStack->push($node);
    if($myMin->isEmpty() || $node
<=$myMin->top()){ $myMin->push($node); } } function mypop() { global $myStack; global $myMin; if($myStack->top() == $myMin->top()){ $myMin->pop(); $myStack->pop(); } else{ $myStack->pop(); } } function mytop() {
global $myStack; return $myStack->top(); } function mymin() { global $myMin; return $myMin->top(); }