c++ - 从后到前显示用链表实现的队列

标签 c++ linked-list queue

我目前正在做一个类(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/

相关文章:

c++ - 事件、双重分派(dispatch)和抽象事件处理

java - 将原始数组添加到链表

c - 使用井号(#)符号来指示数据库链表C程序的命令输入换行符?

C 函数,它接收一个结构,并导致它在函数外部发生变化,即使该结构没有作为指针发送

Python 队列 get()/task_done() 问题

java - Semaphore(int permits, boolean fair),fairness到底是做什么的?

c++ - 检查模板参数是否为引用 [C++03]

c++ - std::find_if ——我该如何对此执行 C# FirstOrDefault ?

c++ - 错误:将 ‘const ComplexNumber’ 作为 const ComplexNumber& ComplexNumber::operator-=(const Complex) 的 ‘this’ 参数传递

c++ - EXC 对迭代器的错误访问