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;
}