编程实现队列的建立,測长,打印,入队,出队。
#include<iostream> #include<stdio.h> #include<string.h> #include<conio.h> using namespace std; typedef struct student { int data; struct student *next; }node; typedef struct linkqueue { node *front; node *rear; }queue; queue *create() { queue *q; q=new queue; q->front=NULL; q->rear=NULL; return q; } int length(queue *HQ) { if(HQ==NULL||HQ->rear==NULL) { cout<<"队列的长度为:0"<<endl;//////空队列 return 0; } int i=0; node *p; p=HQ->front; while(p!=NULL) { p=p->next; i++; } cout<<"队列的长度为:"<<i<<endl;//////更新队列的长度 return i; } void print(queue *HQ) { node *p; p=HQ->front; cout<<"队列中的元素:";////// if(p==NULL) { cout<<"空队列"<<endl;////// return ; } while(p!=NULL) { cout<<p->data<<" ";//打印 p=p->next; } cout<<endl; } queue *insert(queue *HQ,int num) { node *s; s=(node *)malloc(sizeof(node)); s->data=num; s->next=NULL; cout<<s->data<<"入队。";////// if(HQ->front==NULL)//if(HQ->rear==NULL)//在空队列中进行元素入队操作 { HQ->front=s; HQ->rear=s; } else { HQ->rear->next=s; HQ->rear=s; } cout<<endl; return HQ; } queue *dele(queue *HQ) { node *p;int x; cout<<"出队:";////// if(HQ->front==NULL)//HQ->reat==NULL//在空队列中进行元素出队操作 printf("空队列"); else { x=HQ->front->data; p=HQ->front; cout<<x; if(HQ->front==HQ->rear)//队列中仅仅有一个元素 { HQ->front=NULL; HQ->rear=NULL; } else { HQ->front=HQ->front->next; } free(p); } cout<<endl; return HQ; } void main() { queue *HQ; HQ=create(); HQ=dele(HQ);//对空队列进行出队操作 int n; HQ=insert(HQ,10);//入队 HQ=insert(HQ,2); HQ=insert(HQ,3); HQ=insert(HQ,4); HQ=insert(HQ,5); HQ=insert(HQ,6); n=length(HQ); print(HQ); HQ=dele(HQ);//出队 HQ=dele(HQ); HQ=dele(HQ); HQ=dele(HQ); HQ=dele(HQ); HQ=dele(HQ); n=length(HQ); print(HQ); HQ=dele(HQ);//对空队列进行出队操作 n=length(HQ); print(HQ); }执行结果: