【问题标题】:Do you need a previous node pointer to implement a Queue?您是否需要前一个节点指针来实现队列?
【发布时间】:2021-02-11 15:26:41
【问题描述】:

我在这里寻找一些澄清/确认。

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

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

谢谢!

【问题讨论】:

  • 已经回答了,但是前后的操作仅限于push_front()和pop_back()。也可能有 peek 操作,例如 peek_back(),虽然 peek_front() 是可能的,但它是不寻常的。

标签: javascript linked-list stack queue


【解决方案1】:

对于队列,您可以通过使用 2 个指针来实现单链表:一个指向头部,一个指向尾部。所以,不需要使用双向链表。
这是我从GeeksForGeeks 那里得到的实现:

#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 

【讨论】:

    【解决方案2】:

    没有。我们也可以从单链表中实现队列。我们只需要跟踪我们可以通过指针执行的第一个和最后一个元素的内存地址。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      相关资源
      最近更新 更多