简体   繁体   English

从后到前显示通过链接列表实现的队列

[英]Displaying A Queue Implemented with a Linked List from Rear to front

I am currently working on a project for class that requires me to implement a queue with a linked list without using a library. 我目前正在为一个类项目工作,该项目要求我在不使用库的情况下使用链接列表实现队列。 So far my project is working perfectly but when I push_back() 1, 3, 5, 7 the screen displays it with the front of the queue on the left. 到目前为止,我的项目运行良好,但是当我push_back()1、3、5、7时,屏幕将其显示在左侧,队列的前面。 I would prefer it to look Rear on the left such as REAR 7 5 3 1 FRONT. 我希望它在左侧显示“后”,例如REAR 7 5 3 1 FRONT。 What exactly am I missing here that would help me do this? 我在这里到底缺少什么可以帮助我做到这一点?

#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";
}

If you are comfortable with recursion, and have some faith that your system has sufficient stack for the size of Queues you plan, this can work. 如果您对递归感到满意,并且确信系统中有足够的堆栈来满足您计划的队列大小,则可以使用此功能。

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
}

FYI: on ubuntu 12.04 and 4 Gig of ram, I believe I do not experience stack overflows until more than 100K elements in the queue. 仅供参考:在ubuntu 12.04和ram的4 Gig上,我相信直到队列中的元素超过100K时,我才不会遇到堆栈溢出。 Your results will vary ... 您的结果会有所不同...


If you don't have faith, simply transfer the contents of your queue into a vector, then show the vector contents in reverse. 如果您没有信心,只需将队列中的内容转移到向量中,然后反向显示向量内容。

And since it is easy, and you want to avoid using a library, simply use an array. 而且由于它很容易,并且您希望避免使用库,因此只需使用数组即可。

为什么不能简单地反转display()中的循环,使其从后方开始并向着前方移动?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM