队列的入队,出队,测长,打印操作

来源:互联网 发布:淘宝退款不退货的 教程 编辑:程序博客网 时间:2024/04/28 02:16
#include "stdafx.h"#include <iostream>//队列using namespace std;typedef struct node{node *next;//指向链表下一个节点int data;}node;//node表示队列中的每个节点元素,queue表示队列typedef struct queue {node *front;//队首node *rear;//队尾}queue;//创建空队列queue *CreateQueue(){queue *q=new queue;q->front=NULL;//把队首指针置空q->rear=NULL;//把队尾指针置空return q;}//入队,从队尾一端插入节点queue *EnQueue(queue *q,int data){if (q==NULL){//如果指针为NULL,返回NULLreturn NULL;}node *pnode=new node;pnode->data=data;pnode->next=NULL;if (q->rear==NULL){//如果队列为空,则新节点即是队首又是队尾q->rear=q->front=pnode;}else{ //如果队列不为空,新节点放在队尾,队尾指针指向新节点q->rear->next=pnode; //末尾节点的指针指向新节点q->rear=pnode;      //末尾指针指向新节点}return q;}//出队,从队头一端删除节点queue *QuQueue(queue *q){        node *pnode=NULL;pnode=q->front; //指向队头if (pnode==NULL){ //如果队列为空,则返回NULLcout<<"Empty queue!\n";return NULL;}q->front=q->front->next; //把头节点的下一个节点作为头节点if (q->front==NULL){ //若删除后队列为空,需对rear置空q->rear=NULL;}delete pnode; //释放内存    return q;}//队列的测长int GetLength(queue *q){if (q==NULL || q->rear==NULL){return 0;}int i=1;node *pnode=q->front;while (pnode->next!=NULL){ pnode=pnode->next; i++;}return i;}//队列的打印void Print(queue *q){node *pnode=q->front;if (pnode==NULL){//如果队列为空,直接返回cout<<"Empty queue!\n";return;}while (pnode!=NULL){cout<<pnode->data<<" ";pnode=pnode->next;}cout<<endl;}int _tmain(int argc, _TCHAR* argv[]){queue *pA=NULL;pA=CreateQueue();pA=EnQueue(pA,2);pA=EnQueue(pA,3);pA=EnQueue(pA,4);pA=EnQueue(pA,5);Print(pA);cout<<"The Length:"<<GetLength(pA)<<endl;pA=QuQueue(pA);pA=QuQueue(pA);Print(pA);cout<<"The Length:"<<GetLength(pA)<<endl;    system("pause");delete [] pA;return 0;}

 

 

原创粉丝点击