/* Queue 1:队列初始化 void init 2:元素装入队列 void push 3:首元素出队列 void pop 4:取队列首元素 front 5:取队列尾元素 back 6:获取队列的长度 int size 7:队列清空 void Destroy 8:队列判空 bool IsEmpty
*/
#include <iostream> using namespace std; typedef struct node{ int value; struct node *pNext; }Node; typedef struct queue{ int Count; Node* Head; Node *End; }Queue; /*创建队列节点*/ Node* Create(int value) { Node* ptr = new Node; ptr->value = value; ptr->pNext = NULL; return ptr; } /*初始化队列*/ void init(Queue* &queue) { if(queue != NULL) return ; queue = new Queue; queue->Head = NULL; queue->End = NULL; queue->Count = 0; } /*元素装入队列*/ void push(Queue* &queue,Node* node) { if(node == NULL) return ; if(queue->Head == NULL){ queue->Head = node; } else{ queue->End->pNext = node; } queue->End = node; queue->Count++; } /*元素出队列*/ void pop(Queue* &queue) { if(queue == NULL) return ; Node* ptr = queue->Head; if(queue->Head == queue->End){ queue->End = NULL; queue->Head = NULL; } else{ queue->Head = ptr->pNext; } queue->Count--; delete ptr ; ptr = NULL; } /*取队首元素*/ Node* front(Queue* queue) { if(queue == NULL || queue->Head == NULL) return NULL; Node* ptr = queue->Head; return ptr; } /*取队尾元素*/ Node* back(Queue* queue){ if(queue == NULL || queue->End == NULL) return NULL; Node* ptr = queue->End; return ptr; } /*获取队列的长度*/ int size(Queue* queue) { if(queue == NULL || queue->Head == NULL) return 0; return queue->Count; } /*队列销毁*/ void Destroy(Queue* &queue) { while(queue->Count){ pop(queue); } queue->Head = NULL; queue->End = NULL; } /*队列判空*/ bool IsEmpty(Queue* queue) { return queue->Count>0?0:1; }
int main() { int arr[]={4,3,5,6,4,7}; Queue* queue = NULL; /*初始化队列*/ init(queue); Node* ptr = NULL; for(int i=0;i<sizeof(arr)/sizeof(int);i++){ ptr = new Node; /*创建节点*/ ptr->value = arr[i]; /*节点装入队列*/ push(queue,ptr); } /*获取队列的长度*/ cout<<"Queue size:"<<size(queue)<<endl; /*取队列首元素*/ ptr = front(queue); cout<<"Queue front:"<<ptr->value<<endl; /*取队列尾元素*/ ptr = back(queue); cout<<"QUeue back:"<<ptr->value<<endl; /*弹出队列首元素*/ pop(queue); /*队列判空*/ bool empty = false; empty = IsEmpty(queue); if(empty == false){ cout<<"Queue is not Empty"<<endl; } else{ cout<<"Queue is Empty"<<endl; } /*销毁队列*/ Destroy(queue); empty = IsEmpty(queue); if(empty == false){ cout<<"Queue is not Empty"<<endl; } else{ cout<<"Queue is Empty"<<endl; } system("pause"); return 0; }