[PHP data structure] stack related logical operations

Time:2021-10-18

For the logical structure, we also start from the simplest. Stack and queue are not unfamiliar to most people, but heap and stack are actually two things. Don’t be dazed by the interviewer during the interview. Heap is a tree structure, or a complete binary tree structure. Today, we are mainly talking about the application of this stack.

What is a stack?

Stack is generally a sequential data structure. Its biggest feature is last in first out (LIFO), or conversely, first in last out (Filo) is also possible. What exactly do these two sentences mean? The most typical example is what you will definitely see when watching TV dramas, especially gun battles: magazines.

https://imgs.developpaper.com/imgs/1575433-20210722085602780-2027183647.jpg

When the magazine is loaded, the bullets are pressed into the magazine one by one, that is, the first bullet is pressed at the bottom, and when shooting, it bounces out of the top of the magazine in the opposite order, and the first bullet is the last one.

This example is actually very vivid. Let’s unify the terms again. Pressing the bullet into the magazine is called “stacking”. The first bullet is at the bottom, which is called “bottom of the stack”. The last bullet is at the top, which is called “top of the stack”. The bullet hit is the bullet at the “top of the stack”. This operation is called “out of the stack”.

Through the definition of the above terms, we can see that the logical operation of the stack is mainly “entering the stack” and “leaving the stack”, and what the logical structure needs to care about most is the state of the “top of the stack” and “bottom of the stack” when entering and leaving the stack. Of course, there is no problem with the logical structure of the stack using sequential or chain structure. Let’s take a look at it one by one.

Sequential stack

First of all, it is a relatively simple implementation of sequential stack. Since it is a sequential structure, it is an array. However, we also need to record the “top” or “bottom” of the stack, so we encapsulate the array of sequential stacks into a class. At the same time, define an attribute in this class to indicate the “top” or “bottom” pointer of the current stack, which is actually the subscript position of the current “top” or “bottom” in the array. Generally speaking, we only need to record the position of the “top of the stack”, and the “bottom of the stack” can be defaulted to – 1. Because the array subscript itself starts from 0, when the “top of stack” attribute is – 1, the stack is an empty stack, because its “top of stack” and “bottom of stack” are together, and there are no elements in it.

class SqStack
{
    public $data;
    public $top;
}

Initializing the order stack is simple, an empty array and setting $top to – 1.

function InitSqStack()
{
    $stack = new SqStack();
    $stack->data = [];
    $stack->top = -1;
    return $stack;
}

The next step is the “stack in” and “stack out” operations. Let’s look at the code first.

function PushSqStack(SqStack &$stack, $x){
    $stack->top ++;
    $stack->data[$stack->top] = $x;
}

function PopSqStack(SqStack &$stack){
    //Stack empty
    if($stack->top == -1){
        return false;
    }

    $v = $stack->data[$stack->top];
    $stack->top--;
    return $v;
}

Stacking is very simple. Add content to the array elements, and then $Top + + is OK. However, if it is C language, because it has the limit of array length, we also need to judge whether the stack is full when entering the stack. Of course, we don’t have this concern in PHP.

Sequential stacking diagram

https://imgs.developpaper.com/imgs/1575433-20210722085602969-1039153580.jpg

When you exit the stack, you need to judge whether the current stack is empty. This does not distinguish between languages, because if it is smaller than – 1, you will have problems using the stack again. If the stack is empty when it comes out of the stack, don’t give $top — again, and then get the top element of the stack and return it.

Sequential stack out diagram

https://imgs.developpaper.com/imgs/1575433-20210722085603189-555939639.jpg

Let’s take a look at the test results of this sequential stack.

$stack = InitSqStack();

PushSqStack($stack, 'a');
PushSqStack($stack, 'b');
PushSqStack($stack, 'c');

var_dump($stack);
// object(SqStack)#1 (2) {
//     ["data"]=>
//     array(3) {
//       [0]=>
//       string(1) "a"
//       [1]=>
//       string(1) "b"
//       [2]=>
//       string(1) "c"
//     }
//     ["top"]=>
//     int(2)
//   }

echo PopSqStack($stack), PHP_EOL; // c
echo PopSqStack($stack), PHP_EOL; // b
echo PopSqStack($stack), PHP_EOL; // a

var_dump($stack);
// object(SqStack)#1 (2) {
//     ["data"]=>
//     array(3) {
//       [0]=>
//       string(1) "a"
//       [1]=>
//       string(1) "b"
//       [2]=>
//       string(1) "c"
//     }
//     ["top"]=>
//     int(-1)
//   }

Is it very simple to manipulate the stack through an array. After reading and learning the chain stack, we will also talk about the array stack operation function that PHP has prepared for us. It will be more convenient to use.

Chain stack

In fact, for the chain storage structure, the core content is the same. We should also care about our stack top and the operation in and out of the stack. However, in the chain, we can make the header insertion method, that is, keep the inserted data at the top of the chain to achieve the effect of “stack top”. In this way, we don’t need a special attribute to save the current stack top position. It will be clearer to understand directly through a diagram.

https://imgs.developpaper.com/imgs/1575433-20210722085603393-905203765.jpg

class LinkStack{
    public $data;
    public $next;
}

The data structure is a typical chain structure. It is mainly to see how the stack operation is carried out.

function InitLinkStack(){
    return null;
}

function PushLinkStack(?LinkStack &$stack, $x){
    $s = new LinkStack();
    $s->data = $x;
    $s->next = $stack;
    $stack = $s;
}

function PopLinkStack(?LinkStack &$stack){
    if($stack == NULL){
        return false;
    }
    $v = $stack->data;
    $stack = $stack->next;
    return $v;
}

In fact, the operation of initializing an empty stack in the chain stack is of little significance. We can directly define a null variable and then perform chain operation on it, but here we still maintain the unity with the sequence stack. Just as the bottom of the sequential stack is – 1, in the chain stack, we also agree that the bottom of the stack is a null object node.

The next step is the stack operation. Here we use the head insertion method, which is actually putting new elements at the top of the linked list. First instantiate a node, and then point the next node to the head node of the linked list. Then let the current node become the new head node of the linked list, as shown in the following figure.

https://imgs.developpaper.com/imgs/1575433-20210722085603633-1211640513.jpg

Similarly, the stack out operation is similar. Turn the header node into the next node of the current header node until the current node becomes null, that is, the stack is empty, as shown in the figure:

https://imgs.developpaper.com/imgs/1575433-20210722085603854-1307816578.jpg

Finally, let’s also test how the code of this set of chain stack works.

$stack = InitLinkStack();

PushLinkStack($stack, 'a');
PushLinkStack($stack, 'b');
PushLinkStack($stack, 'c');

var_dump($stack);
// object(LinkStack)#3 (2) {
//     ["data"]=>
//     string(1) "c"
//     ["next"]=>
//     object(LinkStack)#2 (2) {
//       ["data"]=>
//       string(1) "b"
//       ["next"]=>
//       object(LinkStack)#1 (2) {
//         ["data"]=>
//         string(1) "a"
//         ["next"]=>
//         NULL
//       }
//     }
//   }

echo PopLinkStack($stack), PHP_EOL; // c
echo PopLinkStack($stack), PHP_EOL; // b
echo PopLinkStack($stack), PHP_EOL; // a

var_dump($stack);
// NULL

Have many friends seen that we spent four articles on the important role of sequential list and linked list in linear structure. They are really the basis of all other logical structures. Not only the stack, we will have linear and chained implementations with different structures in queues, trees and graphs. Of course, it is more important to understand the differences between them. In different business scenarios, two different storage structures may really bring completely different experiences.

Array stack operation provided by PHP

Finally, let’s take a brief look at the two array manipulation functions that have been prepared for us in PHP. With them, for the sequential stack, our operation can be simplified to the effect of very stupid intelligence.

$sqStackList = [];

array_push($sqStackList, 'a');
array_push($sqStackList, 'b');
array_push($sqStackList, 'c');

print_r($sqStackList);
// Array
// (
//     [0] => a
//     [1] => b
//     [2] => c
// )

array_pop($sqStackList);
print_r($sqStackList);
// Array
// (
//     [0] => a
//     [1] => b
// )

echo count($sqStackList) > 0 ? $sqStackList[count($sqStackList) - 1] : false, PHP_EOL;
// b

array_pop($sqStackList);

echo count($sqStackList) > 0 ? $sqStackList[count($sqStackList) - 1] : false, PHP_EOL;
// c

array_pop($sqStackList);

print_r($sqStackList);
// Array
// (
// )

It is estimated that many students have used these two functions for a long time. array_ Push () is to push a data into the array. In fact, to put it bluntly, it is just to add a data to the array. There is no special function. And array_ Pop () pops up the data at the last position of the array. Is it the same concept as the sequential stack we implemented above. Yes, since the language environment is ready for us, we can easily implement stack operation in PHP by directly using these two functions in most cases, except for chain structure in some scenarios.

summary

Is the logical structure of stack very simple and clear? In fact, stack is widely used in daily applications. For example, the transformation of prefix, infix and suffix expressions in expressions. For example, when we learn trees and graphs later, we should contact BFS (deep search), and then introduce the concept of recursion according to BFS. In addition, some symmetric matching when parsing characters and the judgment of palindrome algorithm are typical applications of stack. It can be said that stack supports half of computer algorithms. And the other half? Of course, that’s what we’re going to talk about next time: queues.

Test code:

https://github.com/zhangyue0503/Data-structure-and-algorithm/blob/master/3. Stack and queue / source / 3.1 stack related logical operations.php

reference material:

Data structure, Second Edition, Yan Weimin

Data structure, Second Edition, Chen Yue

High score notes on data structure, 2020 edition, tianqin postgraduate entrance examination

Official account: hard core project manager

Add wechat / QQ friends: [xiaoyuezigonggong / 149844827] get free PHP and project management learning materials

Tiktok, official account, voice, headline search, hard core project manager.

Station B ID: 482780532