PHP/Data Structure/Stack

Материал из Web эксперт
Перейти к: навигация, поиск

array_pop: Pop the element off the end of array

   <source lang="html4strict">

<?php

  $states = array("Ohio","New York","California","Texas");
  $state = array_pop($states); // $state = "Texas"
  print_r($states);

?>

      </source>
   
  


array_push: Push one or more elements onto the end of array

   <source lang="html4strict">

<?php $states = array("Ohio","New York"); array_push($states,"California","Texas"); // $states = array("Ohio","New York","California","Texas"); print_r($states); ?>

      </source>
   
  


A stack with type restricted to int

   <source lang="html4strict">

<? class IntStack {

  var $the_stack;
  var $count = 0;
  
  function push ($intvar) {
     if (is_integer($intvar)) {
         $this->the_stack[$this->count] = $intvar; 
         $this->count++;
         print("Push of $intvar succeeded.
"); } else { print("Hey, IntStack is for ints only!
"); } } function pop () { if ($this->count > 0) { $this->count--; // decrement count $top = $this->the_stack[$this->count]; return($top); } else { print("Hey, the stack is empty!
"); } }

}


$my_stack = new IntStack; $my_stack->push(1); $my_stack->push(49); $my_stack->push("A"); $pop_result = $my_stack->pop(); print("Top of the stack was $pop_result
"); $pop_result = $my_stack->pop(); print("Top of the stack was $pop_result
"); $pop_result = $my_stack->pop(); print("Top of the stack was $pop_result
");

?>

      </source>
   
  


Stack in Use

   <source lang="html4strict">

<html> <head> <title>Stack</title> </head> <body> <?php

    $stack = array();
  
    $book_one = "One";
    $book_two = "Two";
    $book_three = "Three";
  
    array_push($stack, $book_one);
    array_push($stack, $book_three);
    array_push($stack, $book_two);
  
    $n = count ($stack);
    while ($book = array_pop ($stack)) {
         print ("Item $n: $book
\n"); $n--; }

?> </body> </html>

      </source>