Je veux construire une pile implémentée dans PHP. Initialement, j'ai ce code: et initialiser la classe normalement em> à l'aide de ce: p> Ceci est correct et courir. Cependant, je veux initialiser ma pile avec une valeur initiale comme celle-ci: p> Comment puis-je implémenter cela? P> Notez que tous les autres Les fonctions (par exemple, la pop et la poussée) sont fonctionnelles. p> p>
5 Réponses :
simple, changez votre constructeur:
Préparez-vous à avoir une réponse populaire Sir!. =)
Voici la mise en œuvre de la classe de pile correcte. Pour initialiser correctement la matrice à la valeur d'une pile, vous devez inverser les valeurs de ce tableau, comme ceci: codage heureux! P> p> P>
Modifiez votre constructeur comme suit:
<?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));
Sidenote: I> Il est fortement recommandé de valider les paramètres d'entrée du constructeur (vérifiez son type au moins).
changer le constructeur à ceci. Avec cela, vous pouvez fournir une valeur sans valeur, ni une valeur unique, ou plusieurs valeurs dans un tableau. Il lancera une erreur si les valeurs comptent plus grandes que la limite.
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); }
Stack à l'aide de PHP (approche de procédure) forte>
Juste fyi, php a
array_push code> ( PHP.net/ Manuel / fr / Function.Array-push.php ) et
array_pop code> ( US3.php.net/array_pop ) implémentations.
sidenote: i> the
pile $ code> et
$ limite code> peut être
privé code>
Oui mais ça a l'air plus soigné si tu as raison?
Il existe apparemment également une implémentation plus rapide et plus complète en PHP déjà, voir PHP .NET / manuel / fr / classe.ds-stack.php .