PHP/Data Structure/Stack

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

array_pop: Pop the element off the end of array

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



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

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



A stack with type restricted to int

<?
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.<BR>");
      } else {
        print("Hey, IntStack is for ints only!<BR>");
      }
   }
   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!<BR>");
      }
   }
}
 
 
$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<BR>");
$pop_result = $my_stack->pop();
print("Top of the stack was $pop_result<BR>");
$pop_result = $my_stack->pop(); 
print("Top of the stack was $pop_result<BR>");

?>



Stack in Use

<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<br />\n");
          $n--;
     }
?>
</body>
</html>