队列模拟(queue)

可先了解链表相关知识:链表(单向链表的建立、删除、插入、打印) - 蓝海人 - 博客园

队列模拟(queue)_第1张图片

// queue.h -- interface for a queue
#ifndef QUEUE_H_
#define QUEUE_H_
// This queue will contain Customer items
class Customer
{
private:
    long arrive;        // arrival time for customer 顾客的到达时间
    int processtime;    // processing time for customer 顾客的处理时间
public:
    Customer() : arrive(0), processtime (0){} //构造,初始化到达时间和等待处理时间
    void set(long when); //随机初始化客户等待时间,when是到达时间
    //类间函数
    long when() const { 
        return arrive; 
    }
    int ptime() const { 
        return processtime; 
    }
};

typedef Customer Item; //简化声明

//队列类
class Queue
{
private:
// class scope definitions
    // Node is a nested structure definition local to this class
    //节点,嵌套的结构体定义,一个节点里面包括当前的Customer类和下一个节点的指针
    struct Node { 
        Item item; 
        struct Node * next;
    };
    enum {Q_SIZE = 10};
// private class members
    //队列的头指针,尾指针,当前队列中Customer类数量,以及要求的队列最大数量
    Node * front;       // pointer to front of Queue
    Node * rear;        // pointer to rear of Queue
    int items;          // current number of items in Queue
    const int qsize;    // maximum number of items in Queue
    // preemptive definitions to prevent public copying
    Queue(const Queue & q) : qsize(0) { } //拷贝构造,并初始化qsize
    Queue & operator=(const Queue & q) { return *this;}
public:
    Queue(int qs = Q_SIZE); // create queue with a qs limit
    ~Queue();
    bool isempty() const;   //判断队列是否为空
    bool isfull() const;    //判断队列是否为满
    int queuecount() const; //当前队列中类数量
    bool enqueue(const Item &item); // add item to end 添加类到队列尾
    bool dequeue(Item &item);       // remove item from front 删除队列头的类
};
#endif

将类加入队列:

 队列模拟(queue)_第2张图片

 将类出队:

队列模拟(queue)_第3张图片

 

// queue.cpp -- Queue and Customer methods
#include "queue.h"
#include          // (or stdlib.h) for rand()

// Queue methods
Queue::Queue(int qs) : qsize(qs) //在构造函数{}执行前,给qsize赋值qs
{
    front = rear = NULL;    // or nullptr
    items = 0;
}

Queue::~Queue()
{
    Node * temp;
    //从链表头开始,依次删除所有的节点
    while (front != NULL)   // while queue is not yet empty
    {
        temp = front;       // save address of front item
        front = front->next;// reset pointer to next item
        delete temp;        // delete former front
    }
}

bool Queue::isempty() const
{
    return items == 0;
}

bool Queue::isfull() const
{
    return items == qsize;
}

int Queue::queuecount() const
{
    return items;
}

// Add item to queue
bool Queue::enqueue(const Item & item)
{
    if (isfull())   //如果队列满,直接返回false
        return false;
    Node * add = new Node;  // create node 创建一个新节点
// on failure, new throws std::bad_alloc exception 如果失败,会抛出异常

    //创建一个新节点时,先赋值item类对象,再将下一个节点的指向置为NULL
    add->item = item;       // set node pointers
    add->next = NULL;       // or nullptr;

    items++;    //队列存储值+1

    //做判断,如果队列头指向空,则让队列头指向新节点,否则把队列尾指向新节点
    if (front == NULL)      // if queue is empty,
        front = add;        // place item at front
    else
        rear->next = add;   // else place at rear

    rear = add;             // have rear point to new node
    return true;
}

// Place front item into item variable and remove from queue
bool Queue::dequeue(Item & item)
{
    if (front == NULL)
        return false;
    item = front->item;     // set item to first item in queue
    items--;
    Node * temp = front;    // save location of first item
    front = front->next;    // reset front to next item
    delete temp;            // delete former first item
    if (items == 0)
        rear = NULL;
    return true;
}

// customer method

// when is the time at which the customer arrives
// the arrival time is set to when and the processing
// time set to a random value in the range 1 - 3
//随机初始化客户等待时间
void Customer::set(long when)
{
    processtime = std::rand() % 3 + 1;
    arrive = when; 
}
// bank.cpp -- using the Queue interface
// compile with queue.cpp
#include 
#include  // for rand() and srand()
#include    // for time()
#include "queue.h"
const int MIN_PER_HR = 60;

bool newcustomer(double x); // is there a new customer?

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    using std::ios_base;
// setting things up
    std::srand(std::time(0));    //  random initializing of rand()

    cout << "Case Study: Bank of Heather Automatic Teller\n";
    cout << "Enter maximum size of queue: ";
    int qs;
    cin >> qs;  //假设输入3,队列中最多存3个类对象
    Queue line(qs);         // line queue holds up to qs people,初始化Queue::Queue(int qs) : qsize(qs) 

    cout << "Enter the number of simulation hours: "; //程序模拟的持续时间
    int hours;              //  hours of simulation
    cin >> hours;
    // simulation will run 1 cycle per minute 
    //每次循环为1分钟,这里输入1个小时,即60分钟
    long cyclelimit = MIN_PER_HR * hours; // # of cycles

    cout << "Enter the average number of customers per hour: ";
    double perhour;         //  average # of arrival per hour,平均每小时的客户数
    cin >> perhour;
    double min_per_cust;    //  average time between arrivals
    min_per_cust = MIN_PER_HR / perhour;

    Item temp;              //  new customer data 初始化Customer() : arrive(0), processtime (0){} 
    long turnaways = 0;     //  turned away by full queue
    long customers = 0;     //  joined the queue
    long served = 0;        //  served during the simulation
    long sum_line = 0;      //  cumulative line length
    int wait_time = 0;      //  time until autoteller is free
    long line_wait = 0;     //  cumulative time in line


// running the simulation
    for (int cycle = 0; cycle < cyclelimit; cycle++)
    {
        if (newcustomer(min_per_cust))  // have newcomer
        {
            if (line.isfull())
                turnaways++;
            else
            {
                customers++;
                temp.set(cycle);    // cycle = time of arrival,赋值到达时间,随机初始化客户等待时间
                line.enqueue(temp); // add newcomer to line
            }
        }
        if (wait_time <= 0 && !line.isempty()) //如果等待时间为0且队列非空
        {
            line.dequeue (temp);      // attend next customer
            wait_time = temp.ptime(); // for wait_time minutes
            line_wait += cycle - temp.when();
            served++;
        }
        if (wait_time > 0)
            wait_time--;
        sum_line += line.queuecount();
    }

// reporting results
    if (customers > 0)
    {
        cout << "customers accepted: " << customers << endl;
        cout << "  customers served: " << served << endl;
        cout << "         turnaways: " << turnaways << endl;
        cout << "average queue size: ";
        cout.precision(2);
        cout.setf(ios_base::fixed, ios_base::floatfield);
        cout << (double) sum_line / cyclelimit << endl;
        cout << " average wait time: "
             << (double) line_wait / served << " minutes\n";
    }
    else
        cout << "No customers!\n";
    cout << "Done!\n";
    // cin.get();
    // cin.get();
    return 0;
}

//  x = average time, in minutes, between customers
//  return value is true if customer shows up this minute
bool newcustomer(double x)
{
    return (std::rand() * x / RAND_MAX < 1); 
}

你可能感兴趣的:(C/C++,链表,c++)