연결 리스트 큐(헤드 노드 있음) 애니메이션 데모 애니메이션으로 코드를 시각화하세요

图码-数据结构可视化动画版

在本文中,讨论并实现了 队列数据结构 的链表实现。 如果队列为空,则打印“-1”。

方法: 要解决该问题,请遵循以下想法:

我们维护两个指针, front after front 指向队列的第一项, rear 指向最后一项。

  • enQueue(): 该操作在rear后面添加一个新节点 ,并将rear移动 到下一个节点。
  • deQueue(): 该操作删除前面的节点并将前面的节点移动 到下一个节点。

请按照以下步骤解决问题:

  • 创建一个类 QNode,其数据成员为整数 data 和 QNode* next
    • 参数化构造函数,采用整数 x 值作为参数,并将数据设置为等于 x ,并将 next 设置为 NULL
  • 创建一个类Queue,数据成员QNode 前后
  • 带参数 x 的入队操作:
    • 使用 data = x 初始化 QNode* temp
    • 如果后部设置为 NULL,则将前部和后部设置为 temp 并返回(Base Case)
    • 否则将后部设置为 温度旁边,然后将后部移至温度
  • 出队操作:
    • 如果前面设置为NULL则返回(Base Case)
    • 使用 front初始化 QNode temp 并将 front 设置为其下一个
    • 如果前面等于NULL 则将后面设置为NULL
    • 从内存中删除温度

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
struct QNode {
    int data;
    QNode* next;
    QNode(int d)
    {
        data = d;
        next = NULL;
    }
};
 
struct Queue {
    QNode *front, *rear;
    Queue() { front = rear = NULL; }
 
    void enQueue(int x)
    {
 
        // Create a new LL node
        QNode* temp = new QNode(x);
 
        // If queue is empty, then
        // new node is front and rear both
        if (rear == NULL) {
            front = rear = temp;
            return;
        }
 
        // Add the new node at
        // the end of queue and change rear
        rear->next = temp;
        rear = temp;
    }
 
    // Function to remove
    // a key from given queue q
    void deQueue()
    {
        // If queue is empty, return NULL.
        if (front == NULL)
            return;
 
        // Store previous front and
        // move front one node ahead
        QNode* temp = front;
        front = front->next;
 
        // If front becomes NULL, then
        // change rear also as NULL
        if (front == NULL)
            rear = NULL;
 
        delete (temp);
    }
};
 
// Driver code
int main()
{
 
    Queue q;
    q.enQueue(10);
    q.enQueue(20);
    q.deQueue();
    q.deQueue();
    q.enQueue(30);
    q.enQueue(40);
    q.enQueue(50);
    q.deQueue();
    cout << "Queue Front : " << ((q.front != NULL) ? (q.front)->data : -1)<< endl;
    cout << "Queue Rear : " << ((q.rear != NULL) ? (q.rear)->data : -1);
}
// This code is contributed by rathbhupendra


            

C

Java

Python3

C#

Javascript

输出

队列前面:40
队列后方:50

时间复杂度: O(1),enqueue()和dequeue()操作的时间复杂度都是O(1),因为它只改变两个操作中的几个指针辅助空间:O(1),两个操作的
辅助 空间enqueue() 和 dequeue() 的复杂度为 O(1),因为需要恒定的额外空间

相关文章:
队列简介及数组实现

시험 합격, 직업 발전, 또는 순수한 관심 등 어떤 목표를 가지고 있든, 이 데이터 구조 및 알고리즘 시각화 웹사이트는 귀중한 자원이 될 것입니다.

이 웹사이트로 이동하여 학습 여정을 시작하세요!

다음은 일반적인 것들입니다: 【C 언어 설명】《데이터 구조와 알고리즘》데이터 구조 JAVA 구현 데이터 구조와 알고리즘 기초 (칭다오 대학 - 왕줘) 데이터 구조와 알고리즘 왕도 데이터 구조 C 언어 구현 속성 데이터 구조 기말고사 전 구급 데이터 구조 비디오 C 언어판 튜토리얼 데이터 구조 옌웨이민 데이터 구조 하오빈 데이터 구조 대학원 시험 JAVA 데이터 구조 알고리즘과 기초 데이터 구조 왕도 2022 데이터 구조 학습 데이터 구조 샤오자위 왕줘 데이터 구조 학습 데이터 구조 저장 대학 데이터 구조 복습 데이터 구조 마사빙 데이터 구조 기초 제로 데이터 구조와 알고리즘 데이터 구조 입문 대학원 시험 데이터 구조 문제 풀이 설명 데이터 구조 기말 복습 컴퓨터 2급