队列(类)

#include <iostream>
using namespace std;
template <class Type>
struct Node
{
    Type value;
    Node *next;
};
template <class Type>
class Queue
{
public:
    Queue()
    {
        head = tail = NULL;
        length = 0;
    }
    void in(Type value)
    {
        Node<Type> *temp = new Node<Type>;
        temp -> value = value;
        temp -> next = NULL;
        if (head == NULL)
            head = temp;
        if (tail != NULL)
            tail -> next = temp;
        tail = temp;
        length++;
    }
    Type out()
    {
        Type value;
        Node<Type> *temp = head;
        if (length == 0)
        {
            cerr << "队列是空的!" << endl;
            throw(1);
        }
        else if (length == 1)
        {
            head = tail = NULL;
            value = temp -> value;
        }
        else
        {
            value = temp -> value;
            head = temp -> next;
        }
        delete temp;
        length--;
        return value;
    }
    void printAll()
    {
        Node<Type> *temp = head;
        if (length == 0)
        {
            cout << "队列是空的!" << endl;
        }
        else
        {
            cout << "队列中的元素为:";
            do
            {
                cout << temp -> value << " ";
                temp = temp -> next;
            } while (temp != NULL);
            cout << endl;
        }
    }
    int getLength()
    {
        return length;
    }
private:
    Node<Type> *head, *tail;
    int length;
};

int main()
{
    Queue<int> q1;
    q1.printAll();
    for (int i = 1; i <= 5; i++)
    {
        q1.in(i);
    }
    q1.printAll();
    cout << q1.out() << endl;
    q1.printAll();
    cout << endl;

    Queue<char> q2;
    char ch;
    while ((ch = cin.get()) != '\n')
    {
        q2.in(ch);
    }
    q2.in('\0');
    while ((ch = q2.out()) != '\0' )
    {
        cout << ch;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值