[C++ Implementation Queue]

Summary: In this issue, we mainly study the structure of columns and the realization of operations on columns.

1. Queue

Queue is a commonly used data structure with distinctive features:
1. Elements can only be enqueued at one end, and elements can be dequeued at the other end.
2. The elements that enter the queue first go out of the queue first.

The specific structure is shown in the figure below:
insert image description here

Second, the implementation of the operation of the queue

0. Stack structure and initialization
class DoubleLinkedListQueue
{
    
    
private:
    class Element
    {
    
    
    public:
        QString data;
        Element *next;//指向下一个元素
        Element *pre;//指向上一个元素
    };

    int length;

    Element *head;//队首元素
    Element *tail;//队尾元素
public:
    DoubleLinkedListQueue();
};
DoubleLinkedListQueue::DoubleLinkedListQueue()
{
    
    
    //初始化空队列,
    tail = new Element;
    tail->pre = nullptr;
    tail->next = nullptr;
    tail->data = "";

    head = new Element;
    head = tail;//队首等于队尾

    length = 0;
}

1. Join the team

void DoubleLinkedListQueue::push(QString data)
{
    
    
    Element *_elem = new Element;
    _elem->data = data;
    if(head == tail)//空队列
    {
    
    
        _elem->next = nullptr;
        head->next = _elem;
        _elem->pre = head;
        tail = _elem;//队尾元素指向入队元素
    }
    else
    {
    
    
        _elem->next = head->next;
        head->next->pre = _elem;
        _elem->pre = head;
        head->next = _elem;
    }
    length++;
    qDebug()<<data<<QStringLiteral("入队成功!")<<endl;
}

2. Dequeue

void DoubleLinkedListQueue::pop()
{
    
    
    if(length <=0)
    {
    
    
        qDebug()<<QStringLiteral("队列为空,出队失败!")<<endl;
        return;
    }
    Element *_elem = tail;
    tail = _elem->pre;  //队尾元素指向出队元素的前一个元素
    tail->next = nullptr;
    delete _elem;
    _elem = NULL;
    length--;
    qDebug()<<QStringLiteral("出队成功!")<<endl;
}

3. Print the elements in the queue

void DoubleLinkedListQueue::DisplayDoubleLinkedListQueue()
{
    
    
    Element *_elem = head->next;
    int i = 0;
    qDebug()<<QStringLiteral("队列大小为:")<<length<<endl<<QStringLiteral("队列中元素如下:");
    while(i < length)
    {
    
    
        qDebug()<<_elem->data<<" "<<endl;
        _elem = _elem->next;
        i++;
        if(_elem == NULL)
        {
    
    
            return;
        }
    }
}

end

This is the end of the study of queues in this issue, and we will learn about double-ended queues in the next issue:)

Guess you like

Origin blog.csdn.net/wddkxg/article/details/129319824