队列是另一种限定存取位置的线性表。它只允许在表的一头插入(队尾rear),在另一头删除(队头front)。
链式队列就是基于单链表存储,队列的头指针指向单链表的第一个结点,队尾指针指向单链表的最后一个给结点。
链表队列的实现:
#include<iostream> using namespace std; typedef int T; struct Node //链栈节点 { T data; //数据域 Node *next; //指针域 }; class LinkedQueue { public: LinkedQueue():rear(NULL),front(NULL){} //构造函数,建立空队列 ~LinkedQueue(){makeEmpty();}; bool EnQueue(T x); //将x加入队列 bool DeQueue(T& x); //删除队头元素u,x反回其值 bool getFront(T& x)const; //查看队头元素值 void makeEmpty(); bool IsEmpty()const { return (front == NULL)?true:false; } int getSize(); protected: Node *front, *rear; //队头队尾指针 }; void LinkedQueue::makeEmpty() { Node *p; while(front!=NULL) { p = front; front = front->next; delete p; } } bool LinkedQueue::EnQueue(T x) { if(front == NULL) { Node *node = new Node; node->data = x; //cout<<x<<" "<<node->data<<endl; front = rear = node;//空队列时,新节点成为队列的第一个结点,即是队头又是队尾 if(front == NULL) return false;//分配结点失败 } else{ Node *node = new Node;//创建一个新节点 node->data = x; //cout<<x<<" "<<node->data<<endl; rear->next = node;//连接在队尾 if(rear->next == NULL) return false;//分配结点失败 rear = rear->next; } //cout<<front->data<<endl; return true; } bool LinkedQueue::DeQueue(T& x) { if(IsEmpty() == true) return false; Node *p = front; x = front->data; front = front->next; delete p; return true; } bool LinkedQueue::getFront(T& x)const { if(IsEmpty()==true) return false; x = front->data; //cout<<x<<endl; return true; } int LinkedQueue::getSize(){ int len = 0; Node *p = front; while(p != NULL) { p = p->next; len++; } return len; } int main() { LinkedQueue queue; int i=0; int k=0; for(i=1;i<=3;i++){ queue.EnQueue(i); } cout<<"队列长度为:"<<queue.getSize()<<endl; queue.getFront(k); cout<<"队首元素为:"<<k<<endl; cout<<"执行出队操作"<<endl; for(i=0;i<3;i++){ queue.DeQueue(k); cout<<k<<endl; } cout<<"队列长度为:"<<queue.getSize()<<endl; return 0; }
运行截图: