算法:队列的实现

queue.h

#ifndef _QUEUE_H
#define _QUEUE_H

struct Node;
typedef int ElementType;
typedef struct Node *PtrToNode;
typedef PtrToNode Queue;

int IsEmpty(Queue Q);
Queue CreateQueue(void);
void MakeEmpty(Queue Q);
void EnQueue(ElementType X,Queue Q);
void DeQueue(Queue Q);
PtrToNode Last(Queue Q);

#endif

struct Node
{
    ElementType element;
    PtrToNode Next;
};

queue.c

#include <stdlib.h>
#include <stdio.h>
#include "queue.h"

int IsEmpty(Queue Q)
{
    return Q->Next==NULL;
}
Queue CreateQueue(void)
{
    PtrToNode Q;
    Q=malloc(sizeof(struct Node));
    if(Q==NULL){
        printf("out of space");
        exit(1);
    }
    if(Q->Next!=NULL){
        MakeEmpty(Q);
    }
    return Q;
}
void MakeEmpty(Queue Q)
{
    PtrToNode P,temp;
    P=Q->Next;
    Q->Next=NULL;
    while(P!=NULL){
        temp=P;
        P=P->Next;
        free(P);
    }
}
void EnQueue(ElementType X,Queue Q)
{
    PtrToNode P,L;
    P=malloc(sizeof(struct Node));
    if(P==NULL){
        printf("out of space");
    }
    P->element=X;
    L=Last(Q);
    L->Next=P;
}
PtrToNode Last(Queue Q)
{
    PtrToNode P;
    P=Q;
    while(P->Next!=NULL){
        P=P->Next;
    }
    return P;
}
void DeQueue(Queue Q)
{
    PtrToNode P;
    if(Q->Next!=NULL){
        P=Q->Next;
        Q->Next=P->Next;
        free(P);
    }
}

 

posted @ 2017-03-07 21:31  jmst  阅读(218)  评论(0编辑  收藏  举报