队列是一种先进先出的数据结构,其实现如下
数组实现
#include<iostream>
#include<cstring>
using namespace std;
const int MAX = 5;
template <class T>
class queue_array{
int head, rear, m_size;
T data[100];
public:
queue_array(){
head = rear = -1;
m_size = MAX;
memset(data, 0, sizeof(data));
}
void enqueue(T x){
if(rear == m_size - 1) cout << "full\n";
else data[++rear] = x;
}
T dequeue(){
if(rear == head) {cout << "empty\n"; exit(0);}
else return data[++head];
}
bool is_empty(){
return head == rear;
}
int size(){
return rear - head;
}
};
int main(){
queue_array<int> q;
return 0;
}
链表实现
#include<iostream>
using namespace std;
template <class T>
class node{
public:
T data;
node<T> *next;
node(){
data = NULL;
next = NULL;
}
node(T x, node<T> *ptr){
data = x;
next = ptr;
}
};
template <class T>
class queue_linknode{
node<T> *head, *rear;
int cnt = 0;
public:
queue_linknode(){
head = new node<T>();
rear = new node<T>();
}
void push(T x){
node<T> *t = new node<T>(x, NULL);
if(cnt == 0){head = rear = t;}
else{rear->next = t; rear = t;}
cnt++;
}
T pop(){
if(cnt == 0){cout << "empty\n"; exit(0);}
T t = head->data;
head = head->next;
cnt--;
return t;
}
bool is_empty(){
return cnt == 0;
}
int size(){
return cnt;
}
};
int main(){
queue_linknode<int> q;
return 0;
}