我目前正在做一个类(class)项目,该项目要求我在不使用库的情况下使用链表实现队列。到目前为止,我的项目运行良好,但是当我 push_back() 1, 3, 5, 7 时,屏幕显示它并在左侧队列的前面。我更喜欢它看起来像 Rear 在左边,例如 REAR 7 5 3 1 FRONT。我到底缺少什么可以帮助我做到这一点?
#include "queue.h"
#include <iostream>
Queue::Queue()
{
queue_size = 0;
front = 0;
rear = 0;
}
Queue::~Queue()
{
delete front;
delete rear;
}
void Queue::push_back(int x)
{
node * q = new node;
q->data = x;
q->next = 0;
if(this->isEmpty())
{
front = q;
front ->next = 0;
rear = front;
}
else
{
rear->next = q;
rear = rear->next;
rear->next = 0;
}
queue_size = queue_size + 1;
}
void Queue::pop_front(int &num)
{
node * temp;
num = front->data;
temp = front;
front = front ->next;
delete temp;
queue_size = queue_size - 1;
}
bool Queue::isEmpty()
{
if(front == 0)
return true;
else
return false;
}
int Queue::ret_size()
{
return queue_size;
}
void Queue::display()
{
node * temp;
temp = front;
for(int i = 0; i < queue_size; i++)
{
std::cout<<temp->data<< " ";
temp = temp->next;
}
std::cout<<"\n";
}
最佳答案
如果您对递归感到满意,并且相信您的系统有足够的堆栈来满足您计划的队列大小,那么这可以工作。
void Queue::display(void)
{
node* temp;
temp = front;
if(temp)
temp->displayR();
std::cout<<"\n";
}
void Queue::displayR(void)
{
if(m_next)
m_next->displayR(); // spin down to end of queue
// now display the current data
std::cout << data << " "; // report end of queue first
}
仅供引用:在 ubuntu 12.04 和 4 Gig ram 上,我相信我不会遇到堆栈溢出,直到队列中的元素超过 100K。您的结果会有所不同...
如果您没有信心,只需将队列的内容传输到 vector 中,然后反向显示 vector 内容即可。
因为它很简单,而且您想避免使用库,只需使用数组即可。
关于c++ - 从后到前显示用链表实现的队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805643/