[PHP data structure] Application of stack and queue


Through the study of stack and queue, we seem to feel that the data structure is still very simple. Of course, this is just the beginning. We start from the sequence list and linked list to the current stack and queue, which are actually to pave the way for the future. Stack and queue can be seen in the traversal algorithm of tree and graph. Here, let’s take a brief look at some practical applications of stack and queue.

Palindrome question

Suppose there is a text, we have to judge whether it is “palindrome” (not the text of Hui Brothers). You can apply the stack to solve this problem.

Palindrome means that after the text is divided into two, the content of the previous paragraph is exactly the same as that of the next paragraph, but the order is opposite. For example, it is very famous that Shanghai’s tap water comes from the sea. Shanghai comes from the sea. Such a two-stage structure constitutes a palindrome in one sentence. Another example is an even length character: abcddcba, which is also a palindrome.

In fact, similar questions are easy to appear in some simple algorithm interview questions. I believe many small partners have seen the clue. We can put the first half into the stack, and then go out of the stack one by one. By comparing with the second half, we can judge whether the current string is a palindrome. Don’t just talk but practice, let’s implement it in code.

$string1 = 'abcdedcba';
$string2 = 'abcdeedcba';
$string3 = 'abcdefcba';

function getIsPlalindrome($string)
    if (gettype($string) != 'string') {
        return false;
    $strlen = strlen($string);
    $mid = floor($strlen / 2);
    $arr = [];

    if ($strlen < 2) {
        return false;

    for ($i = 0; $i < $mid; $i++) {
        array_push($arr, $string[$i]);

    $j = $mid;
    $i = $strlen % 2 == 0 ? $ mid : $mid + 1; // $ I starting from the median
    for (; $i < $strlen; $i++) {
        $v = $arr[$j - 1]; //  Get stack top element
        if ($v != $string[$i]) {
            return false;
        array_ pop($arr); //  Pop up stack top element
    if ($arr) {
        return false;
    return true;

var_dump(getIsPlalindrome($string1)); // bool(true)
var_dump(getIsPlalindrome($string2)); // bool(true)
var_dump(getIsPlalindrome($string3)); // bool(false)

It’s very simple. It’s using array_ Push() and array_ Pop () to perform sequential stack operations. The only thing to note is that the median we want to take will change accordingly for different odd and even character lengths.

Palindrome algorithm is still relatively simple. In addition, questions such as simple bracket matching, arithmetic operation and infix to suffix expression often appear, which are typical algorithm interview questions of stack. You can find the relevant content to try.


Before talking about recursion, we should make it clear that function calls in programming languages are essentially stack calls.

How do you understand this sentence? When we execute code, if we encounter a function, we will always enter the function first. After running the code in the function, we will return to the original code execution line to continue to execute the code calling the current function. For example, the following code.

function testA()
    echo 'A start.', PHP_EOL;
    echo 'A end.', PHP_EOL;
function testB()
    echo 'B start.', PHP_EOL;
    echo 'B end.', PHP_EOL;
echo 'P start.', PHP_EOL;
echo 'P end.', PHP_EOL;

// P start.
// A start.
// B start.
// B end.
// A end.
// P end.

When the current page P runs to the testa() function, it enters the testa() function and executes its internal code, that is, P – > a. Then the testa() function calls the testb() function, so now it enters testb() and executes the code in the function body, that is, P – > A – > B. When the code of testb () is completed, return to testa () to continue to execute the contents in the body of the testa () function, and finally return to page p to continue to execute downward, that is, B – > A – > P.

If you don’t understand the above paragraph once, please read it a few more times and taste it carefully. This is a stack calling process!!


From this point of view, stack really exists in the bone marrow of programming language. Because as long as you are developing code, you must be using stack. Recursion is a more typical implementation of stack.

function recursion($n)
    if ($n == 0 || $n == 1) {
        return 1;
    $result = recursion($n - 1) * $n;
    return $result;

echo recursion(10), PHP_EOL;

This is a recursive implementation of a simple factorial algorithm. Because recursion will establish a stack, the first thing we calculate in this code is that N at the bottom of the stack is 1. After returning 1, we multiply 1 by 2, and then continue to multiply 2 by 3, and so on, until the factorial result from 1 to 10 is calculated.


The interview questions related to recursion are also very common in our interview, so we must grasp that recursion is actually a form of stack, and then use the idea of stack to deconstruct the whole recursive call process.

Queue application

Finally, let’s talk about some practical applications of queues. In fact, there are not many good examples of queues at the code level. Common problems are that two queues are merged out of the team (dance partner problem) or two groups of queues are out of the team together, and one can only be out of the other. You can find relevant topics by yourself. Relatively speaking, the queue algorithm questions are still relatively few in the interview questions, including in the postgraduate entrance examination, most of them are questions such as choice judgment. However, in practical application, queue is now a super magic weapon to solve high concurrency problems, and it is also an important content for the interviewer to judge your experience.

In the actual project development, the most typical function of queue is the second kill problem. Just like grabbing train tickets or Xiaomi mobile phones, at the hour, a large number of requests pour in. If only rely on the server to handle them, the ultra-high concurrency will not only bring great pressure to the server, but also problems that may occur in various high concurrency scenarios, such as oversold, transaction exceptions, etc. (multiple threads update data at the same time)

The queue is a good hand to solve this problem. The queue systems we usually use (redis, rabbitmq) are memory based queue systems, which are characterized by very fast storage. A large number of requests generated by the front end (producer) are queued (queued) and then processed (queued) in the background script (consumer). The front end only needs to return a prompt that is being processed or queued, and then notify the foreground to display the results after the background processing is completed. In this way, in a second kill scenario, the problem of high concurrency is basically solved. Of course, more factors may need to be considered in the real environment, but the core is to solve this instantaneous high concurrency business function in the form of queue.


In addition, there is another important business scenario in the queue, that is, the sending of such information as notifications, messages, emails and SMS. Because the queue can solve some problems, the biggest feature is the need for producer / consumer business decoupling. Usually, when we send messages in groups, we will send them in batches. At this time, we only need to prepare the message content and the corresponding mobile phone number and device ID, so that the system can send messages slowly in the background queue, instead of waiting for all messages to be sent all the time.

At this time, many friends saw a little way again. In practical applications, queues are multi-threaded. Event callback in JS and CPU fragment time polling are not real applications of queues. There is also the “observer mode” in the design mode, which itself is a programming paradigm of the mechanism of event callback. Therefore, we can see the shadow of queue in many functions implemented by it.


Look, a stack and a queue are all things we have to contact every day in the development process. Do you feel your brain capacity is not enough? Think again, what else is related to our stack and queue? In fact, just grasp their two essence: stack is last in first out (LIFO) or first in last out (Filo), and queue is first in first out (FIFO).

Test code:

https://github.com/zhangyue0503/Data-structure-and-algorithm/blob/master/3. Stack and queue / source / 3.3 stack and queue application.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