编程实现队列的入队、出队、测长、打印

来源:互联网 发布:衬衣品牌 知乎 编辑:程序博客网 时间:2024/04/30 06:10
<span style="font-size:18px;">//使用单链表实现队列的入队、出队、测长、打印#include<iostream>using namespace std;typedef int elemtype;  typedef struct node{elemtype data;node *next;}node;typedef struct queue{node *front;node *rear;}queue;//构造空的队列queue *CreatQueue(){queue *p=(queue*)malloc(sizeof(queue));p->front=NULL;p->rear=NULL;return p;}//入队,从队尾一段插入节点queue *inqueue(queue *q ,elemtype  data){node *newp=(node*)malloc(sizeof(node));newp->data=data;newp->next=NULL;if(q->front==NULL){q->front=q->rear=newp;}else{q->rear->next=newp;q->rear=newp;}return q;}//出队,从队头一段删除节点queue *outqueue(queue *q ){node *pnode=NULL;pnode=q->front;if(pnode==NULL){cout<<"队列为空"<<endl;}else{q->front=q->front->next;free(pnode);}return q;}//打印队列void PrintQueue(queue *q){node *pnode=q->front;if(pnode==NULL){cout<<"队列为空"<<endl;}else{while(pnode!=q->rear){cout<<pnode->data<<" ";pnode=pnode->next;}}cout<<pnode->data<<endl;}//测量队列的长度int  LengthQueue(queue *q){int n=0;node *pnode=q->front;if(pnode!=NULL){n=1;}while(pnode!=q->rear){pnode=pnode->next;n++;}return n;}int main(){queue *myq;myq=CreatQueue();//入队int data;while(cin>>data){inqueue(myq ,  data);}//队列的长度int len;len= LengthQueue(myq);cout<<"队列的长度:";cout<<len<<endl;PrintQueue(myq);outqueue(myq );PrintQueue(myq);return 0;}</span>

0 0