2013-11-26 2 views
3

Я хочу построить стек, реализованный в PHP. Изначально у меня есть этот код:PHP Stack Implementation

class Stack 
{ 
    protected $stack; 
    protected $limit; 

    public function __construct($limit = 10) { 
     // initialize the stack 
     $this->stack = array(); 
     // stack can only contain this many items 
     $this->limit = $limit; 
    } 

    public function push($item) { 
     // trap for stack overflow 
     if (count($this->stack) < $this->limit) { 
      // prepend item to the start of the array 
      array_unshift($this->stack, $item); 
     } else { 
      throw new RunTimeException('Stack is full!'); 
     } 
    } 

    public function pop() { 
     if ($this->isEmpty()) { 
      // trap for stack underflow 
      throw new RunTimeException('Stack is empty!'); 
     } else { 
      // pop item from the start of the array 
      return array_shift($this->stack); 
     } 
    } 

    public function top() { 
     return current($this->stack); 
    } 

    public function isEmpty() { 
     return empty($this->stack); 
    } 
} 

И инициализировать класс обычно с помощью этого:

$stack = new Stack(); 
$stack->push(1); 
$stack->push(2); 
$stack->push(3); 
$stack->push(4); 
$stack->push(5); 

Это правильно и работает. Тем не менее, я хочу инициализировать мой стек с таким начальным значением:

$stack = new Stack(array(1,2,3,4,5)); 

Как это реализовать?


Обратите внимание, что все другие функции (например, поп и толчок) являются функциональными.

+2

Просто FYI, PHP имеет реализацию 'array_push' (http://php.net/manual/en/function.array-push.php) и' array_pop' (http://us3.php.net/array_pop) , – adeelx

+0

* sidenote: * '$ stack' и' $ limit' могут быть 'private' – Raptor

+0

Да, но это выглядит более аккуратно, если у вас есть эти права? –

ответ

3

Измените конструктор следующим образом:

<?php 

class Stack { 

    protected $stack; 
    protected $limit; 

    public function __construct($limit = 10, $initial = array()) { 
     // initialize the stack 
     $this->stack = $initial; 
     // stack can only contain this many items 
     $this->limit = $limit; 
    } 

    public function push($item) { 
     // trap for stack overflow 
     if (count($this->stack) < $this->limit) { 
      // prepend item to the start of the array 
      array_unshift($this->stack, $item); 
     } else { 
      throw new RunTimeException('Stack is full!'); 
     } 
    } 

    public function pop() { 
     if ($this->isEmpty()) { 
      // trap for stack underflow 
      throw new RunTimeException('Stack is empty!'); 
     } else { 
      // pop item from the start of the array 
      return array_shift($this->stack); 
     } 
    } 

    public function top() { 
     return current($this->stack); 
    } 

    public function isEmpty() { 
     return empty($this->stack); 
    } 

} 

/** 
* This'll work as expected. 
*/ 
$stack = new Stack(); 
$stack->push(1); 
$stack->push(2); 
$stack->push(3); 
$stack->push(4); 
$stack->push(5); 

/** 
* And this too. 
*/ 
$stack = new Stack(10, array(1, 2, 3, 4, 5)); 

Просто FYI, PHP имеет array_push (http://php.net/manual/en/function.array-push.php) и array_pop (http://us3.php.net/array_pop) реализации.

+0

* sidenote: * ВЫСОКО рекомендуется проверять входные параметры в конструкторе (по крайней мере, проверьте его тип). – Raptor

1

Простой, изменить конструктор:

public function __construct($limit = 10, $values = array()) { 
    // initialize the stack 
    $this->stack = $values; 
    // stack can only contain this many items 
    $this->limit = $limit; 
} 
+0

Подготовьтесь к популярному ответу sir!. =) –

+0

Это неверно. Однако у меня появилась идея. –

2

Вот реализация соответствующего класса стека. Для того, чтобы правильно инициализировать массив значения стеки, вы должны полностью изменить значение этого массива, как это:

class Stack 
{ 
    protected $stack; 
    protected $limit; 

    public function __construct($values = array(),$limit = 10) { 
     // initialize the stack 
     $this->stack = array_reverse($values); 
     // stack can only contain this many items 
     $this->limit = $limit; 
    } 

    public function push($item) { 
     // trap for stack overflow 
     if (count($this->stack) < $this->limit) { 
      // prepend item to the start of the array 
      array_unshift($this->stack, $item); 
     } else { 
      throw new RunTimeException('Stack is full!'); 
     } 
    } 

    public function pop() { 
     if ($this->isEmpty()) { 
      // trap for stack underflow 
      throw new RunTimeException('Stack is empty!'); 
     } else { 
      // pop item from the start of the array 
      return array_shift($this->stack); 
     } 
    } 

    public function top() { 
     return current($this->stack); 
    } 

    public function isEmpty() { 
     return empty($this->stack); 
    } 
} 

Счастливого кодирование!

0

Измените конструктор на это. При этом вы не можете указать значение или одно значение или несколько значений в массиве. Он выдает ошибку, если значения превышают лимит.

public function __construct($limit = 10, $values = null) { 
     // stack can only contain this many items 
     $this->limit = $limit; 
     // initialize the stack 
     $this->stack = array(); 
     if (is_null($values)) $values = array(); 
     else if (!is_array($values)) $values = array($values); 
     foreach ($values as $value) $this->push($value); 
    } 

Там, надеюсь, это поможет.