【问题标题】:C++ Printing a queue in reverse without using a stack or doubly linked listC++ 在不使用堆栈或双向链表的情况下反向打印队列
【发布时间】:2016-02-02 01:58:08
【问题描述】:

我的部分任务是按照链表队列的相反顺序打印我们的代码输出。我和我的导师谈过,他说他不希望用堆栈来完成。如果没有将队列转换为堆栈的选项,他也不希望将其设为双向链表,我不知道如何打印。有谁知道我想念的方式?我已经包含了我写的所有内容。任何想法都会被考虑并提前致谢。

#include <iostream>
#include <fstream>
using namespace std;

class queue{
 public:
 queue();
 void enq(int);
 void deq();
 int front();
 bool isEmpty();
 void printq();  //print que in reverse
private:
 struct node{
     int val;
     node* next;
  };
node* topPtr;
};

queue::queue()
{
topPtr = NULL;
}

void queue::enq(int x)
{
if (topPtr == NULL)
{
    topPtr = new node;
    topPtr->val = x;
    topPtr->next = NULL;
}
else
{
    node* tmp;
    tmp = topPtr;
    while (tmp->next != NULL)
    {
        tmp = tmp->next;
    }
    tmp->next = new node;
    tmp = tmp->next;
    tmp->next = NULL;
    tmp->val = x;
  }
}

void queue::deq()
{
node* rem = topPtr;
topPtr = topPtr->next;
delete(rem);
}

int queue::front()
{
return topPtr->val;
}

bool queue::isEmpty()
{
if (topPtr == NULL)
    return true;
else
    return false;
}

void queue::printq()
{
      ////totally lost here
}

int main()
 {
  ifstream cmds("cmd.txt");
  int cmd, op;
  queue s;
  bool isEmpty;

while (cmds >> cmd)
{
    switch (cmd)
    {
    case 1:
        cmds >> op;
        s.enq(op);
        break;
    case 2:
        s.deq();
        break;
    case 3:
        cout << "Top: " << s.front() << endl;
        break;
    case 4:
        empty = s.isEmpty();
        if (empty)
            cout << "queue is empty" << endl;
        else
            cout << "queue is not empty" << endl;
        break;
    case 5:     //print case

    }
  }
  return 0;
}

【问题讨论】:

  • 每次要添加新项目时,请检查当前队列大小。添加新项目,然后删除所有先前存在的项目,并立即将每个项目重新添加到队列中。添加完所有项目后,请正常删除并打印它们。

标签: c++ linked-list queue


【解决方案1】:

您可以从后面的索引/指针迭代到前面的索引/指针,这取决于您插入的方式(可以交换)。

【讨论】:

    【解决方案2】:

    使用递归函数。

    这样,您就没有明确使用堆栈。但是您正在隐式使用调用堆栈。

    PS:我没有写任何代码或具体说明要做什么,但给出了提示。因为这是一个作业,你应该自己做。

    【讨论】:

      猜你喜欢
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      相关资源
      最近更新 更多