数据结构——链队列
2013-09-05 10:32
447 查看
#include <iostream> using namespace std; typedef struct qnode { int data; struct qnode * next; }Qnode, * Queueptr; // 创建链 Qnode是struct qnode的别名,Queueptr是struct qnode *的别名 typedef struct { Queueptr front; //对头指针 Queueptr rear; //队尾指针 }LinkQueue; //创建队列 //初始化队列 void InitQueue(LinkQueue *Q) { Q->front=(Queueptr) malloc(sizeof(Qnode)); //队头和队尾指向头结点 if(!Q->front) { cout<<"no memory avaliable"<<endl; //存储分配失败 } else { Q->front->next=NULL; Q->rear=Q->front; } } //入队列函数 void Enqueue(LinkQueue *Q,int value) { Queueptr newp=(Queueptr)malloc(sizeof(Qnode)); if(!newp) cout<<"no memory avaliable"<<endl; //存储分配失败 newp->data=value; newp->next=NULL; Q->rear->next=newp; //p插入原队尾 Q->rear=newp; //p成为新的队尾 } //删除队列头函数 int DeQueue(LinkQueue *Q) { int x; Queueptr p=(Queueptr)malloc(sizeof(Qnode)); if(Q->front==Q->rear) cout<<"队列中无元素"<<endl; p=Q->front->next; //指向对头结点 x=Q->front->next->data; //保存对头结点的数据 Q->front->next=p->next; //将对头结点从链上摘下 if(Q->rear==p)//原队中只有一个结点,删去后队列变空,此时队头指针已为空 Q->rear=NULL; free(p); //释放被删队头结点 return x; //返回原队头数据 } //打印队列函数 int PrintQueue(LinkQueue *Q) { if(Q->front==Q->rear) { cout<<"is empty"<<endl; return 0; } Queueptr p=(Queueptr)malloc(sizeof(Qnode)); p=Q->front->next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } return 1; } //取队列头元素 int QueueTop(LinkQueue *Q) { return Q->front->next->data; } //判断队列是否为空 int QueueEmpty(LinkQueue *Q) { return Q->front==Q->rear; } //返回队列的元素个数 int QueueLen(LinkQueue *Q) { Queueptr p=(Queueptr)malloc(sizeof(Qnode)); p=Q->front->next; int count=0; while(p!=NULL) { count++; p=p->next; } return count; } //销毁队列 void DestroyQueue(LinkQueue *Q) { while(Q->front) { Q->rear=Q->front->next; delete Q->front; Q->front=Q->rear; } } int main() { LinkQueue *Q=(LinkQueue *)malloc(sizeof(LinkQueue)); //初始化队列 InitQueue(Q); //入队列操作 int value; cout<<"Input an integer"<<endl; cin>>value; while(value!=0) { Enqueue(Q,value); cin>>value; } PrintQueue(Q); //打印队列 cout<<endl; //出队列操作 cout<<DeQueue(Q)<<endl; PrintQueue(Q); cout<<endl; //取队列顶元素 cout<<"the front elme:"<<endl; cout<<QueueTop(Q)<<endl; //判断队列是否为空 if(QueueEmpty(Q)==1) cout<<"is empty"<<endl; else cout<<"is not empty"<<endl; //返回队列的元素个数 cout<<"队列中还有几个数"<<endl; cout<<QueueLen(Q)<<endl; //显示队列 cout<<"剩余的数是:"<<endl; PrintQueue(Q); cout<<endl; //销毁队列 DestroyQueue(Q); cout<<"销毁之后:"<<endl; PrintQueue(Q); cout<<endl; return 0; }
相关文章推荐
- 数据结构之队列
- 数据结构之队列(一)——概论
- 数据结构之循环队列
- 数据结构——数组模仿循环队列
- 数据结构(七)——队列
- 数据结构之队列(链式队列)
- 数据结构——队列常考知识点
- 【NOIp复习】数据结构之栈、队列和二叉树
- 数据结构之栈和队列
- Java数据结构与算法解析(三)——队列与背包
- 数据结构之链表、栈和队列 java代码实现
- 栈与队列-密码翻译(数据结构基础 第3周)
- 2134 数据结构实验之栈与队列四:括号匹配
- 数据结构之队列
- 数据结构实验之栈与队列二:一般算术表达式转换成后缀式
- 数据结构与算法之栈和队列
- 数据结构之单链表实现队列C++
- Java 数据结构之 Queue(队列)
- 数据结构实验之栈与队列一:进制转换
- 程序员面试宝典之数据结构基础----C++两个栈实现一个队列功能