我希望在这里得到一些澄清/确认。
据我所知,stack可以用单链表实现,因为所有的堆栈操作都是在堆栈的顶部(头部)执行的。换句话说,每个堆栈节点只需要一个指向next
节点的指针。
然而,在队列中,我们需要同时在队列的前面和后面执行操作(即。enqueue()和dequeue())。这是否意味着,正确的队列实现必须建立在双向链表(即,其中每个节点都有next
和previous
指针的链表)?
谢谢!
发布于 2021-02-12 00:00:43
对于队列,可以通过使用两个指针来实现单链表:一个用于头部,一个用于尾部。因此,不需要使用双向链表。
这是我从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
发布于 2021-02-12 20:07:44
不是的。我们也可以从单链表中实现队列。我们只需要保持第一个和最后一个元素的内存地址的跟踪,这可以通过指针来完成。
https://stackoverflow.com/questions/66157655
复制相似问题