1. 程式人生 > >佇列的建立和基本操作

佇列的建立和基本操作

佇列 / 列隊 Queue

//二叉樹
typedef struct Tree{
    int val;
    Tree *left;
    Tree *right;
    //Tree(int v):val(v){}
}*P_Tree;

//佇列
typedef P_Tree Elem;    //以二叉樹作為列隊結點元素
struct Node{
    Elem Data;
    struct Node *Next;  //下一個進來的結點
};
struct QNode{
    struct Node *rear;  //列隊尾(push)
    struct Node *front; //列隊頭(pop)
};
typedef struct QNode* Queue;

Queue createQueue(){
    Queue queue=(Queue)malloc(sizeof(QNode));
    queue->rear=NULL;
    queue->front=NULL;
    return queue;
}

int isEmpty(Queue Q){
    //如果佇列不為空,則其對頭和對尾會指向某個結點
    return (Q->front == NULL);
}

//對尾(rear)push
void push(Elem item,Queue queue){
    Node *next;
    next=(Node*)malloc(sizeof(Node));
    next->Data=item;
    next->Next=NULL;

    if(isEmpty(queue)){
        queue->front=next;
        queue->rear=next;
    }else{
        queue->rear->Next=next;
        queue->rear=next;
    }
}

//隊頭(front)pop
Elem pop(Queue queue){
    struct Node *node;
    Elem item;

    if(isEmpty(queue)){
        cout << "佇列空" << endl;
        return NULL;
    }

    node=queue->front;

    if(queue->front == queue->rear){
        queue->front=NULL;
        queue->rear=NULL;
    }else{
        queue->front=queue->front->Next;
    }

    item=node->Data;
    free(node);
    return item;
}