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

Teach you how to implement stack structure using PHP

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

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

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

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

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

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

    public function __destruct()
    {
        echo 'over ';
    }
}

$stack = new HeapStack();
echo $stack->pushValue('stackValue')."\n";
echo $stack->pushValue('stackValue2')."\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