1. 程式人生 > >資料結構---佇列C語言實現

資料結構---佇列C語言實現

#include <stdio.h>
#include <stdlib.h>
//佇列大小
#define   SIZE  1024
static int  queue[SIZE] = {0};
static int head , tail ; 
//0   1
int Is_Empty(void)
{
    //判斷佇列是否為空,如果頭是尾,就證明為空 
	return  head == tail ; 
}
//0   1
int Is_Full(void)
{   
    //判斷佇列是否已經滿了 
	return (head+1)%SIZE == tail ; 
}
//入隊
int enqueue(int value)
{ 
	if(Is_Full())
	{
		return 1 ; 
	}
	queue[head] = value ; 
	head = (head + 1) % SIZE ; 
	return 0 ; 
}
//出隊
int dequeue(int *value)
{
	if(Is_Empty())
		return 1 ; 
	*value = queue[tail] ; 
	tail = (tail + 1) % SIZE ; 
	return 0 ; 
}

int main(void)
{
    int i ;
    int temp ;
    int buffer[5] = {1,2,3,4,5};
    
    printf("入隊前:\n");    
    for(i = 0 ; i < 5 ; i++)
    {
        printf("queue[%d]:%d\n",i,queue[i]);   
    }
    for(i = 0 ; i < 5 ; i++)
    {
        enqueue(buffer[i]) ;
    }
    printf("入隊後: \n");
    for(i = 0 ; i < 5 ; i++)
    {
        printf("queue[%d]:%d\n",i,queue[i]);   
    }
    printf("出隊後: \n");
    while(1)
    {
        if(dequeue(&temp)) 
            break ; 
        printf("%d\n",temp);
    }
    getchar();
}

執行結果:

入隊前:

queue[0]:0

queue[1]:0

queue[2]:0

queue[3]:0

queue[4]:0

入隊後:

queue[0]:1

queue[1]:2

queue[2]:3

queue[3]:4

queue[4]:5

出隊後:

1

2

3

4

5