懂c++的进来

来源:百度知道 编辑:UC知道 时间:2024/06/14 14:21:33
实验二 队列管理模拟
一、实验内容
队列的创建、入队、出队等操作。
二、实验目的
1.熟悉用C或C++进行程序设计的方法。
2.掌握队列的基本操作:创建、入队、出队等运算。
三、实验题目
队列管理的模拟算法采用如下管理模式:(队列采用链式存储结构)
(1)初始化一个空链队列
(2)当从键盘输入奇数时,奇数从队尾入队列;
(3)当从键盘输入偶数时,若队列不空,则队头出队;
(4)当从键盘输入0时,退出算法;
(5)每输入一个整数,显示操作后队列中的所有值。
【测试数据】:
键盘输入整数:1
打印当前队列: 1
键盘输入一个整数:3
打印当前队列: 1 3
键盘输入一个整数:5
打印当前队列: 1 3 5
键盘输入一个整数:7
打印当前队列: 1 3 5 7
键盘输入一个整数:1
打印当前队列: 1 3 5 7 1
键盘输入一个整数:11
打印当前队列: 1 3 5 7 1 11
键盘输入一个整数:2
打印当前队列: 3 5 7 1 11
键盘输入一个整数:4
打印当前队列: 5 7 1 11
键盘输入一个整数:7
打印当前队列: 5 7 1 11 7
键盘输入一个整数:0
打印当前队列: 5 7 1 11 7 (算法结束)

给分吧,我急用!!

#include <iostream>
using namespace std;

class queue
{
public:
queue();
~queue();
void enque(int n);
void deque();
void print() const;
private:
struct elem {
int val;
elem* next;
} *head, *tail;
int num_elems;
};

queue::queue():head(0),tail(0),num_elems(0)
{}

queue::~queue()
{
if(num_elems != 0)
{
elem* prev = head;
while(head)
{
head = head->next; // 顺序搞反了,已修正,谢tanyuguo指点
delete prev;
}
}
}

void queue::enque(int n)
{
elem* prev = tail;
tail = new elem;
tail->val = n;
tail->next = 0;

if(prev)
prev->next = tail;
if(!head)
head = tail;
++num_elems;
}

void queue::deque()
{
if(!head)
return;
elem* out = head;
head = head->next;