Home >Backend Development >PHP Tutorial >Teach you how to implement stack structure using PHP

Teach you how to implement stack structure using PHP

藏色散人
藏色散人forward
2020-10-09 15:12:585190browse

Teach you how to implement stack structure using PHP

Recommended: "PHP Video Tutorial"

1. Stack definition and knowledge

1. Definition: Stack, also known as stack or stack, is a special serial abstract data type in computer science. The special thing is that it is only allowed at one end of the linked list or array (the top of the stack Pointer, also known as "top") adds data push (push) and output data pop (pop stack). In addition, the stack can also be implemented using one-dimensional arrays and linked lists.

2. Characteristics of the stack:

a. First in, last out (last in, first out), that is to say, we can only add data by push at the top of the stack, and we can only Pop to delete data at the top of the stack;

b. Except for top (top of stack) and base (bottom of stack), every other element in the stack has a predecessor and successor;

2. Simple implementation of stack structure in php

<?php
class HeapStack{
    private $stackArr = array();
    private $stackMaxTop = 10; // 栈顶最大值(用于控制栈长度,是否栈满)
    private $top = -1; // 栈顶(会随着push或pop的操作而变化)
    private $out;

    /**
     * 入栈
     *
     */
    public function pushValue($value=&#39;&#39;)
    {
        if(empty($value))
            return &#39;压入的值不能为空&#39;;

        if($this->top == $this->stackMaxTop)
            return &#39;栈内已满&#39;;
        array_push($this->stackArr, $value);
        ++$this->top;
        return &#39;入栈成功,栈顶值:&#39;.$this->top;
    }

    /**
     * 出栈
     *
     */
    public function popValue()
    {
        if($this->top == -1)
            return &#39;栈内没有数据&#39;;

        $this->out = array_pop($this->stackArr);
        --$this->top;
        return &#39;出栈成功,当前栈顶值:&#39;.$this->top.&#39;出栈值:&#39;.$this->out;
    }

    /**
     * 获取栈内信息
     */
    public function getSatck()
    {
        return $this->stackArr;
    }

    public function __destruct()
    {
        echo &#39;over &#39;;
    }
}

$stack = new HeapStack();
echo $stack->pushValue(&#39;stackValue&#39;)."\n";
echo $stack->pushValue(&#39;stackValue2&#39;)."\n";
var_dump($stack->getSatck());
echo $stack->popValue()."\n";
var_dump($stack->getSatck());

The above is the detailed content of Teach you how to implement stack structure using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete