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

来源:互联网 发布:淘宝打包员有年轻人吗 编辑:程序博客网 时间:2024/04/30 06:55
01.#include "stdafx.h"   02.#include <iostream>   03.//队列   04.using namespace std;  05.typedef struct node{  06.    node *next;//指向链表下一个节点   07.int data;  08.}node;  09.  10.//node表示队列中的每个节点元素,queue表示队列   11.typedef struct queue {  12.node *front;//队首   13.node *rear;//队尾   14.}queue;  15.  16.//创建空队列   17.queue *CreateQueue(){  18.    queue *q=new queue;  19.    q->front=NULL;//把队首指针置空   20.    q->rear=NULL;//把队尾指针置空   21.    return q;  22.}  23.//入队,从队尾一端插入节点   24.queue *EnQueue(queue *q,int data){  25.    if (q==NULL){//如果指针为NULL,返回NULL   26.        return NULL;  27.    }  28.    node *pnode=new node;  29.    pnode->data=data;  30.    pnode->next=NULL;  31.    if (q->rear==NULL){//如果队列为空,则新节点即是队首又是队尾   32.        q->rear=q->front=pnode;  33.    }else{ //如果队列不为空,新节点放在队尾,队尾指针指向新节点   34.    q->rear->next=pnode; //末尾节点的指针指向新节点   35.    q->rear=pnode;      //末尾指针指向新节点   36.    }  37.    return q;  38.}  39.//出队,从队头一端删除节点   40.queue *QuQueue(queue *q){  41.        node *pnode=NULL;  42.        pnode=q->front; //指向队头   43.    if (pnode==NULL){ //如果队列为空,则返回NULL   44.        cout<<"Empty queue!\n";  45.        return NULL;  46.    }  47.    q->front=q->front->next; //把头节点的下一个节点作为头节点   48.    if (q->front==NULL){ //若删除后队列为空,需对rear置空   49.        q->rear=NULL;  50.    }  51.    delete pnode; //释放内存   52.    return q;  53.}  54.//队列的测长   55.int GetLength(queue *q){  56.    if (q==NULL || q->rear==NULL){  57.        return 0;  58.    }  59.    int i=1;  60.    node *pnode=q->front;  61.    while (pnode->next!=NULL){  62.         pnode=pnode->next;  63.         i++;  64.    }  65.    return i;  66.}  67.//队列的打印   68.void Print(queue *q){  69.        node *pnode=q->front;  70.    if (pnode==NULL){//如果队列为空,直接返回   71.        cout<<"Empty queue!\n";  72.        return;  73.    }  74.    while (pnode!=NULL){  75.        cout<<pnode->data<<" ";  76.        pnode=pnode->next;  77.    }  78.    cout<<endl;  79.}  80.int _tmain(int argc, _TCHAR* argv[])  81.{  82.    queue *pA=NULL;  83.    pA=CreateQueue();  84.    pA=EnQueue(pA,2);  85.    pA=EnQueue(pA,3);  86.    pA=EnQueue(pA,4);  87.    pA=EnQueue(pA,5);  88.    Print(pA);  89.    cout<<"The Length:"<<GetLength(pA)<<endl;  90.    pA=QuQueue(pA);  91.    pA=QuQueue(pA);  92.    Print(pA);  93.    cout<<"The Length:"<<GetLength(pA)<<endl;  94.    system("pause");  95.    delete [] pA;  96.    return 0;  97.}