首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >你需要前一个节点指针来实现一个队列吗?

你需要前一个节点指针来实现一个队列吗?
EN

Stack Overflow用户
提问于 2021-02-11 23:26:41
回答 2查看 109关注 0票数 0

我希望在这里得到一些澄清/确认。

据我所知,stack可以用单链表实现,因为所有的堆栈操作都是在堆栈的顶部(头部)执行的。换句话说,每个堆栈节点只需要一个指向next节点的指针。

然而,在队列中,我们需要同时在队列的前面和后面执行操作(即。enqueue()和dequeue())。这是否意味着,正确的队列实现必须建立在双向链表(即,其中每个节点都有nextprevious指针的链表)?

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2021-02-12 00:00:43

对于队列,可以通过使用两个指针来实现单链表:一个用于头部,一个用于尾部。因此,不需要使用双向链表。

这是我从GeeksForGeeks获取的实现

代码语言:javascript
运行
复制
#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); 
    } 
}; 
  
// Driven Program 
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)->data << endl; 
    cout << "Queue Rear : " << (q.rear)->data; 
} 
// This code is contributed by rathbhupendra 
票数 0
EN

Stack Overflow用户

发布于 2021-02-12 20:07:44

不是的。我们也可以从单链表中实现队列。我们只需要保持第一个和最后一个元素的内存地址的跟踪,这可以通过指针来完成。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66157655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档