Data Structures: Stack and Queue Resolution

Table of contents

introduction

1. Stack

1.1 Concept

1.2 Operation

1.3 Implementation

Stack.h

Stack.cpp

1.4 Application scenarios

Two, the queue

2.1 Concept

2.2 Operation

 2.3 Implementation

Queue.h

Queue.cpp

1.4 Application scenarios

3. Comparison of stack and queue

Four. Summary


introduction

In the previous article, readers were introduced to the relatively simple sequential list and linked list in the data structure . This article introduces the stack and queue derived from it . The four structures are all linear structures.

1. Stack

1.1 Concept

A stack is a linear data structure with Last-In-First-Out (LIFO ) characteristics . Imagine you have a stack of books on a table, and every time you put a book down, it gets placed on top. When you need to take out a book, you can only start from the top. This is how the stack works.

In other words, a stack is a special linear table that only allows insertion and deletion of elements at one fixed end. The end where data insertion and deletion operations are performed is called the top of the stack , and the other end is called the bottom of the stack . The data elements in the stack follow the last-in-first-out principle.

1cee7c59dc5b4e51ab9793e8957e6592.png

1.2 Operation

  • Push : Push the element onto the top of the stack.
  • Pop : Pop the element from the top of the stack.
  • Top : Returns the value of the top element of the stack.
  • I sEmpty : Checks if the stack is empty.

1.3 Implementation

Stacks can generally be implemented using arrays or linked lists. Relatively speaking, the structure of arrays is better. However, practical applications require more flexible structures. Dynamic stacks are generally used, and the author’s implementation is also a dynamic method.

Stack.h

#ifndef STACK_STACK_H
#define STACK_STACK_H

#include <cstddef>

typedef int STDataType;

class Stack {
private:
    STDataType *_data; //动态开辟栈空间
    size_t _top;        //指向栈顶元素的下一个位置
    size_t _capacity;   //栈的容量
public:
    //构造函数初始化内部属性并开辟动态空间
    explicit Stack(size_t capacity = 4);

    //析构函数释放开辟内存
    ~Stack();

    //进栈操作
    void push(STDataType value);

    //出栈操作
    void pop();

    //判断栈是否为空
    bool isEmpty();
};

#endif //STACK_STACK_H

Stack.cpp

#include "Stack.h"

// 构造函数初始化内部属性并开辟动态空间
Stack::Stack(size_t capacity) {
    _data = new STDataType[capacity];
    _top = 0;
    _capacity = capacity;
}

// 析构函数释放开辟内存
Stack::~Stack() {
    delete[] _data;
}

// 进栈操作
void Stack::push(STDataType value) {
    if (_top == _capacity) {
        // 栈满时扩展容量
        size_t newCapacity = _capacity * 2;
        STDataType* newData = new STDataType[newCapacity];
        for (size_t i = 0; i < _capacity; ++i) {
            newData[i] = _data[i];
        }
        delete[] _data;
        _data = newData;
        _capacity = newCapacity;
    }
    _data[_top++] = value;
}

// 出栈操作
void Stack::pop() {
    if (_top > 0) {
        --_top;
    }
}

// 判断栈是否为空
bool Stack::isEmpty() {
    return (_top == 0);
}

1.4 Application scenarios

  • Function call: The stack is used to store the context information of the function call, including local variables, return address, etc.
  • Parenthesis matching: The stack can be used to check whether the parentheses in an expression match.
  • Browser History: Browsers use the stack to keep track of the web pages visited, allowing the user to use the "Back" button to return to a previous page.

Two, the queue

2.1 Concept

A queue is a linear data structure with first- in-first-out ( First-In-First-Out, FIFO ) characteristics. It can be imagined as people waiting in line, first come, first served, last come, last served.

In other words, a queue is a special linear table that only allows inserting data at one end and deleting data at the other end. The queue has the characteristics of FIFO (First In First Out).

Into the queue : the end of the insertion operation is called the end of the queue

Out of the queue : the end of the delete operation is called the head of the queue

af261a5bc67e4768b23c3aebdbc549d3.png

2.2 Operation

  • Enqueue : Adds an element to the end of the queue.
  • Dequeue : Removes elements from the front of the queue.
  • Front : Returns the first element of the queue.
  • IsEmpty : Checks if the queue is empty.

 2.3 Implementation

Queue.h

#ifndef QUEUE_QUEUE_H
#define QUEUE_QUEUE_H

#include <cstddef>

typedef int QDataType;

class Queue {
private:
    struct Node {
        QDataType data;
        Node* next;
        Node(QDataType value) : data(value), next(nullptr) {}
    };

    Node* _front;   // 队列的前端
    Node* _rear;    // 队列的后端

public:
    // 构造函数初始化内部属性
    Queue();

    // 析构函数释放内存
    ~Queue();

    // 入队操作
    void enqueue(QDataType value);

    // 出队操作
    void dequeue();

    // 返回队列的第一个元素
    QDataType front();

    // 判断队列是否为空
    bool isEmpty();
};

#endif //QUEUE_QUEUE_H

Queue.cpp

#include "Queue.h"

Queue::Queue() : _front(nullptr), _rear(nullptr) {}

Queue::~Queue() {
    while (_front != nullptr) {
        Node* temp = _front;
        _front = _front->next;
        delete temp;
    }
}

void Queue::enqueue(QDataType value) {
    Node* newNode = new Node(value);
    if (_rear == nullptr) {
        // 如果队列为空,则新节点同时成为队列的前端和后端
        _front = newNode;
        _rear = newNode;
    } else {
        // 如果队列不为空,则将新节点添加到队列的后端
        _rear->next = newNode;
        _rear = newNode;
    }
}

void Queue::dequeue() {
    if (_front != nullptr) {
        // 删除队列的前端节点并更新_front指针
        Node* temp = _front;
        _front = _front->next;
        if (_front == nullptr) {
            // 如果队列为空,则更新_rear指针
            _rear = nullptr;
        }
        delete temp;
    }
}

QDataType Queue::front() {
    if (_front != nullptr) {
        // 返回队列的第一个元素值
        return _front->data;
    }
    // 队列为空时的处理,这里假设元素类型为int,可以根据实际情况进行修改
    return 0;
}

bool Queue::isEmpty() {
    // 判断队列是否为空
    return (_front == nullptr);
}

1.4 Application scenarios

  • Breadth First Search (BFS): Queues are used in the BFS algorithm to manage pending nodes.
  • Buffer management: Queues are often used to process and manage input/output requests, ensuring that they are processed in the order in which they are requested.
  • Multi-thread task scheduling: Queues can be used to manage task scheduling among multiple threads.

3. Comparison of stack and queue

While stacks and queues are similar in some ways (both are linear data structures ), their main difference is how data is inserted and deleted. A stack performs insertions and deletions from one end, while a queue performs these operations from both ends.

In terms of performance , the time complexity of the insertion and deletion operations of stacks and queues is O(1), that is, constant time. However, for other operations on stacks and queues, such as accessing a specific element or searching for a specific element, the time complexity may be higher, depending on the implementation.

Four. Summary

Stacks and queues are important data structures in computer science, and they are widely used in algorithms and programming. The stack has the characteristics of last in first out , which is suitable for scenarios such as function calls and bracket matching. The queue has the characteristics of first-in first-out , which is suitable for scenarios such as breadth-first search and task scheduling.

Understanding the principles and characteristics of stacks and queues, as well as their application scenarios, is crucial to becoming a good programmer. I hope this article will be helpful to readers and further broaden the knowledge and understanding of data structures.

Guess you like

Origin blog.csdn.net/weixin_57082854/article/details/131710207