1. 程式人生 > >佇列中入隊,出隊,遍歷演算法程式碼演示

佇列中入隊,出隊,遍歷演算法程式碼演示

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

typedef struct STR{
    int * Pbase;
    int front;
    int rear;
}QUEUE,*pQueue;
void init(pQueue);
int en_queue(pQueue,int);
int IS_empty(QUEUE);
int IS_full(QUEUE);
int out_queue(pQueue,int*);     //第二個引數,記錄出隊的元素地址
void traverseQueue(QUEUE);
int len = 6;            //定義陣列的長度


int main(int argc, const char * argv[])
{
    QUEUE queue;
    int val = 0;
    init(&queue);
    en_queue(&queue,2);
    en_queue(&queue, 8);
    en_queue(&queue, 8);
    en_queue(&queue, 8);
    en_queue(&queue, 8);
    
    out_queue(&queue, &val);
    printf("出隊成員是:%d \n",val);
    out_queue(&queue, &val);
    printf("出隊成員是:%d \n",val);
    out_queue(&queue, &val);
    printf("出隊成員是:%d \n",val);
    en_queue(&queue, 4);
    en_queue(&queue, 8);
    
    
    
    traverseQueue(queue);
    return 0;
}

void init(pQueue Pque){
    Pque->Pbase = (int*)malloc(sizeof(int)*len);
    Pque->front = 0;
    Pque->rear = 0;
}
int IS_empty(QUEUE queue){
    if (queue.rear == queue.front) {
        printf("佇列為空!\n");
        return 0;
    }
    else
        return 1;
}
int IS_full(QUEUE queue){
    if ((queue.rear+1)%len == queue.front) {
        printf("該佇列已滿!\n");
        return 0;
    }
    else
        return 1;
}
int en_queue(pQueue Pque,int val){
    if (IS_full(*Pque) ==0) {
        return 0;
    }
    else{
        Pque->Pbase[Pque->rear] = val;
        Pque->rear = (Pque->rear+1)%len;  //注意入隊時,rear的增加要對陣列長度取餘
        return 1;
    }
}
int out_queue(pQueue Pque,int* val){
    if (IS_empty(*Pque) == 0) {
        return 0;
    }
    else{
        *val = Pque->Pbase[Pque->front];
        Pque->front = (Pque->front+1)%len;
        return 1;
    }
}

void traverseQueue(QUEUE queue){
    printf("佇列成員有: ");
    while (queue.front != queue.rear) {
        printf("%d ",queue.Pbase[queue.front]);
        queue.front = (queue.front+1)%len;    //迴圈佇列的輸出,個數加一,對長度取餘
    }
    printf("\n");
}

注意:靜態佇列,一定是迴圈佇列.