21xrx.com
2024-09-19 23:58:21 Thursday
登录
文章检索 我的文章 写文章
C++队列实现方法
2023-07-02 13:06:02 深夜i     --     --
C++ 队列 实现方法

队列是一种常见的数据结构,其特点是先进先出。C++中可以使用STL中的队列容器来实现队列,也可以手动实现队列。

1.使用STL中的队列容器

STL中的队列容器是一种封装好的队列,可以直接使用。其基本操作包括入队尾、出队头、获取队头元素、获取队列大小等。

首先需要包含队列头文件:

#include

然后定义队列:

queue q; //定义一个int类型的队列

队列的基本操作如下:

//入队

q.push(1);

q.push(2);

q.push(3);

//出队

q.pop();

//获取队头元素

int head = q.front();

//获取队列大小

int size = q.size();

2.手动实现队列

手动实现队列需要定义一个结构体来表示队列中的一个节点,包含元素值和下一个节点指针。然后定义一个队列类,包含队列头指针和队列尾指针,以及基本操作如入队、出队、获取队头元素、获取队列大小等。

结构体定义如下:

struct Node {

  int data;

  Node* next;

};

队列类定义如下:

class Queue {

public:

  Queue()

    head = NULL;

    tail = NULL;

    count = 0;

  void enqueue(int data) {//入队

    Node* newNode = new Node;

    newNode->data = data;

    newNode->next = NULL;

    if (head == NULL)

      head = newNode;

      tail = newNode;

    else

      tail->next = newNode;

      tail = newNode;

    count++;

  }

  void dequeue() {//出队

    if (head == NULL) return;

    Node* temp = head;

    head = head->next;

    delete temp;

    count--;

  }

  int front() {//获取队头元素

    if (head == NULL) return -1;

    return head->data;

  }

  int size() //获取队列大小

    return count;

private:

  Node* head;//队头指针

  Node* tail;//队尾指针

  int count;//队列大小

};

使用时需要先定义一个队列对象,然后进行基本操作:

Queue q;

q.enqueue(1);

q.enqueue(2);

q.enqueue(3);

q.dequeue();

int head = q.front();

int size = q.size();

以上就是C++队列的实现方法。使用STL中的队列可以方便快捷地实现队列,而手动实现队列可以更好地理解队列的本质和基本操作。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复