队列(类)

版权声明:根号v587版权所有 https://blog.csdn.net/hcmdghv587/article/details/82503391
#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;
}

猜你喜欢

转载自blog.csdn.net/hcmdghv587/article/details/82503391