当前位置:网站首页>Stack, LIFO

Stack, LIFO

2022-06-26 13:21:00 liuliang514218119

<?php

#  After the first out   Stack 
class stack
{
    
    public $data = [];
    public $size;

    public function __construct($size = 10)
    {
    
        $this->size = $size;
    }

    #  Push 
    public function push($element)
    {
    
        if (count($this->data) >= $this->size) {
    
            throw new Exception(" The stack is full ");
            return " The stack is full ";
        }
        array_push($this->data, $element);
    }

    #  Out of the stack 
    public function pop()
    {
    
        if (count($this->data) < 1) {
    
            throw new Exception(" The stack is empty. ");
            return " The stack is empty. ";
        }
        return array_pop($this->data);
    }

    #  To the top of the stack 
    public function get_top()
    {
    
        if (count($this->data) < 1) {
    
            throw new Exception(" The stack is empty. ");
            return " The stack is empty. ";
        }
        return end($this->data);  # Internal pointer to the last element in the array 
    }

    public function get_data()
    {
    
        return $this->data;
    }
}

// Declaration stack 
$stack = new stack();
$stack->push(5);
$stack->push(6);
$stack->push(7);
$stack->push(8);
$stack->push(9);
$stack->pop();

print_r($stack->get_top());
echo "\n";
print_r($stack->get_data());
die;

 Insert picture description here

原网站

版权声明
本文为[liuliang514218119]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261124488517.html