#include <iostream>
using namespace std;
template<typename T> class myQueue;
template<typename T>
class node
{
friend class myQueue<T>;
node(const T& t) : data(t), next(0)
{
}
T data;
node *next;
};
template<typename T>
class myQueue
{
public:
myQueue() : head(0), tail(0), length(0)
{
}
~myQueue()
{
destroy();
}
bool empty() const
{
//return length == 0;
return head == 0;
}
void push(const T&);
T& front() const;
void pop();
int getLen() const;
private:
void destroy();
node<T> *head, *tail;
int length;
};
template<typename T>
void myQueue<T>::push(const T& val)
{
node<T> *p = new node<T>(val);
if(empty())
head = tail = p;
else
{
tail->next = p;
tail = p;
}
length++;
}
template<typename T>
T& myQueue<T>::front() const
{
return head->data;
}
template<typename T>
void myQueue<T>::pop()
{
if(empty())
{
cout << "empty" << endl;
return;
}
else
{
node<T> *p = head;
head = head->next;
delete p;
length--;
}
}
template<typename T>
void myQueue<T>::destroy()
{
while(!empty())
{
pop();
length--;
}
}
template<typename T>
int myQueue<T>::getLen() const
{
return length;
}
int main(void)
{
// myQueue<int> q;
// q.push(1);
// q.push(2);
// q.push(3);
// q.push(4);
// q.push(5);
// myQueue<double> q;
// q.push(1.1);
// q.push(2.2);
// q.push(3.3);
// q.push(4.4);
// q.push(5.5);
myQueue<string> q;
q.push("la");
q.push("lalala");
q.push("hehe");
q.push("hoho");
q.push("get it");
while(!q.empty())
{
int len = q.getLen();
cout << "queue length: " << len << endl;
cout << "front: ";
cout << q.front() << endl;
q.pop();
}
return 0;
}
C++实现队列(链表版)
最新推荐文章于 2024-04-28 18:45:04 发布