双向链表的结点包含前驱指针和后继指针,队列入队操作是在双向链表尾部添加元素,队列的出队操作是把双向链表的头结点删除,判断队列是否为空只要判断双向链表的头指针是否指向了NULL即可。
# include <iostream> # include <cstdlib> using namespace std; struct queueNode { int val; queueNode *pre; queueNode *next; queueNode(int x):val(x),pre(NULL),next(NULL){} }; queueNode *head=NULL; queueNode *tail=NULL; queueNode *cur=head; void push(int x) //入队 { if(head==NULL) { head=new queueNode(x); cur=head; tail=head; } else { queueNode *tmp=new queueNode(x); cur->next=tmp; tmp->pre=cur; cur=tmp; tail=cur; } } bool isempty(queueNode *head) //判断队列是否为空 { return head==NULL; } void pop() //出队 { if(tail==NULL) return ; queueNode *tmp=head; head=head->next; if(head) head->pre=NULL; delete tmp; } int front(queueNode *head) //返回队头元素 { if(isempty(head)) return -1; return head->val; } int main() { push(1); push(2); push(3); cout<<front(head)<<endl; pop(); cout<<isempty(head)<<endl; system("pause"); return 0; }
原文地址:http://blog.csdn.net/u011608357/article/details/38346475