1、数组实现队列(加了模板)
#include <iostream>
using namespace std;
#define MAX 100
//数组实现队列:模板类
template<class T>
class MyList
{
public:
T * buf;
T front;
T rear;
public:
MyList();
~MyList(){
delete [] buf;
buf = NULL;
cout<<"delete MyList"<<endl;
}
bool isempty();
bool isfull();
void push_back(T a);
T pop(); //返回栈顶元素
void ergodic();
};
template<class T>
MyList<T>::MyList(){
buf = new T[MAX];
front = 0;
rear = 0;
}
template<class T>
bool MyList<T>::isempty(){
if(front==rear)
return true;
return false;
}
template<class T>
bool MyList<T>::isfull(){
if((rear+1)%MAX==front)
return true;
return false;
}
template<class T>
void MyList<T>::push_back(T a){
if(isfull()){
return;
}
buf[rear] = a;
rear = (rear+1)%MAX;
}
template<class T>
T MyList<T>::pop(){
if(isempty()){
return -1;
}
T pop_num = buf[front];
front = (front+1)%MAX;
return pop_num;
}
template<class T>
void MyList<T>::ergodic(){
if(isempty()){
return;
}
if(rear>front){
for(int i=front;i<=rear-1;i++){
cout<<"ergodic : "<<buf[i]<<endl;
}
}else if(rear<front){
for(int i=front;i<MAX;i++){
cout<<"ergodic : "<<buf[i]<<endl;
}
for(int i=0;i<rear;i++){
cout<<buf[i]<<endl;
}
}
}
int main ()
{
MyList<int> *mylist =new MyList<int>();
mylist->push_back(5);
mylist->push_back(4);
mylist->push_back(3);
mylist->ergodic();
cout<<"front is : "<<mylist->pop()<<endl;
cout<<"front is : "<<mylist->pop()<<endl;
delete mylist; //调用析构函数,释放内存
mylist = NULL; //讲指针指向NULL 否则将成为野指针
return 0;
}
2、链表实现队列
#include <iostream>
#include <stack>
using namespace std;
//单向链表节点
struct ListNode{
int value;
struct ListNode *Next;
};
class MyQueue
{
public: //成员变量位置
ListNode *Head;
public: //成员函数位置
MyQueue(){
Head = new ListNode; //创建对象的时候调用
}
~MyQueue(){ //析构函数一般用于释放内存
delete Head;
Head = NULL;
}
bool isempty();
void pushback(int n);
void pop();
void ergodic();
};
bool MyQueue::isempty(){
ListNode *P = Head;
if(P==NULL||P->Next==NULL)
return true;
return false;
}
void MyQueue::pushback(int n){
ListNode *P = Head;
while(P->Next!=NULL){
P = P->Next;
}
ListNode *tmp = new ListNode;
tmp->value = n;
tmp->Next =NULL;
P->Next = tmp;
P = tmp;
}
//只有pop不一样,队列是删除第一个节点,栈是删除最后一个节点
void MyQueue::pop(){
if(isempty())
return;
ListNode *P = Head;
P->Next = P->Next->Next;
}
void MyQueue::ergodic(){
if(isempty())
return;
ListNode *P = Head;
while(P->Next!=NULL){
P = P->Next;
cout<<P->value<<endl;
}
}
int main ()
{
MyQueue *mystack = new MyQueue; //自己定义一个对象
mystack->pushback(2);
mystack->pushback(3);
mystack->pushback(4);
mystack->pop();
mystack->ergodic();
delete mystack;
mystack = NULL;
return 0;
}