程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> 用數組去實現隊列(c)

用數組去實現隊列(c)

編輯:關於C
[html]
#include <stdio.h> 
#include <stdlib.h> 
 
struct QueueRecord; 
typedef struct QueueRecord *Queue; 
 
#define MinQueueSize (5) 
 
struct QueueRecord 

    int Capacity; 
    int Front; 
    int Rear; 
    int Size; 
    int *Array; 
}; 
 
/* 
 * 創建 隊列。 
 */ 
Queue CreateQueue(int capacity) 

    Queue queue; 
    queue = (Queue)malloc(sizeof(Queue)); 
    if (queue == NULL) 
    { 
        printf("out of space!!!\n"); 
    } 
    queue->Array = (int *)malloc(capacity * sizeof(int)); 
    if (queue->Array == NULL) 
    { 
        printf("out of space!!!\n"); 
    } 
    queue->Size = 0; 
    queue->Rear = -1; 
    queue->Front = 0; 
     
    return queue; 

 
 
 
/* 
 * if full ,return 0; else return 1; 
 */ 
int IsFull(Queue queue, int capacity) 

    return (queue->Size < capacity); 

 
/* if null return 1. else 0 */ 
int IsEmpty(Queue queue) 

    return (queue->Size == 0); 

 
/* 
 * 打印隊列。 
 */ 
int ShowQueue(Queue queue, int capacity) 

    int i; 
     
    printf("queue->Front = %d\n", queue->Front); 
    printf("queue->Rear = %d\n", queue->Rear); 
    if (!IsEmpty(queue)) 
    { 
        for (i = queue->Front; i <= queue->Rear; i++) 
            { 
                if (i < queue->Rear) 
                { 
                    printf("%d, ", queue->Array[i]);  
                } 
                else 
                { 
                    printf("%d ", queue->Array[i]); 
                } 
 
            } 
    } 
    else 
    { 
        printf("oh, sorry. it is empty."); 
    } 
 

/* 進隊 */ 
void Enqueue(Queue queue, int a, int capacity) 

    queue->Rear++; 
    queue->Array[queue->Rear] = a; 
    queue->Size++; 
 
    if (IsFull(queue, capacity)) 
    { 
        if (queue->Rear == capacity) 
        { 
            queue->Rear = 0; 
        } 
             
    } 
     

 
/* 出隊 */ 
void Dequeue(Queue queue, int capacity) 

    queue->Front++; 
    queue->Size--; 
     
    if (IsFull(queue, capacity)) 
    { 
        if (queue->Front== capacity) 
        { 
            queue->Front = 0; 
        } 
             
    } 

 
int main(void) 

    Queue queue; 
    int capacity = 10; 
    if (capacity < MinQueueSize) 
    { 
        printf("it is too small.\n"); 
    } 
     
    queue = CreateQueue(capacity); 
    Enqueue(queue, 1, capacity); 
    Enqueue(queue, 2, capacity); 
    Enqueue(queue, 3, capacity); 
    Enqueue(queue, 4, capacity); 
    Enqueue(queue, 5, capacity); 
    Enqueue(queue, 6, capacity); 
    Dequeue(queue, capacity); 
    Enqueue(queue, 12, capacity); 
    //Enqueue(queue, 3, capacity); 
    ShowQueue(queue, capacity); 
     




摘自 angelbosj的專欄
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved