队列
#ifndef NODE_H #define NODE_H template <typename T> class node{ public: T data; node<T> *next; public: node(T _data=0) : data(_data),next(nullptr){} }; #endif // NODE_H
#ifndef QUEUE_H #define QUEUE_H #include <iostream> #include "Node.h" using namespace std; template <typename T> class Queue { public: Queue() { head = new node<T>; length=0; } Queue(int sum) { head = new node<T>; length=0; for(int i=0;i<sum;i++) insert(0); } Queue(const Queue& rhs) { head = new node<T>; length=0; node<T> *_node = rhs.head; for(int i=0;i<rhs.length;i++) { insert(_node->next->data); _node = _node->next; } } virtual ~Queue() { int _length = length; for(int i=0;i<_length;i++) erase(); delete head; } Queue& operator =(const Queue& rhs) { if(this == &rhs) return *this; int _length = length; for(int i=0;i<_length;i++) erase(); head->next = nullptr; node<T> *_node = rhs.head; for(int i=0;i<rhs.length;i++) { insert(_node->next->data); _node = _node->next; } return *this; } public: void push(const T& _data) { insert(_data); } void pop() { erase(); } T& top() { if(length == 0) throw std::bad_alloc("bad_alloc"); return head->next->data; } bool empty() const { return length==0; } int size() const { return length; } friend ostream& operator <<(ostream &os, const Queue<T> &queue) { node<T> *_node = queue.head->next; while(_node != nullptr) { os << _node->data << ","; _node = _node->next; } return os; } private: void insert(const T&_data) { node<T>* new_node = new node<T>(_data); node<T>* _head = head; int _length=length; while(_length > 0) { _head = _head->next; _length--; } _head->next = new_node; length++; } void erase() { if(empty()) return; node<T> *del_node = head->next; head->next=del_node->next; delete del_node; length--; } private: node<T> *head; int length; }; #endif // QUEUE_H