1. 程式人生 > >(資料結構)佇列

(資料結構)佇列

佇列,一種線性儲存結構。

特點:1.佇列中的資料是按照“先進先出”的方式進出佇列的。

2.佇列只允許在“隊首”進行刪除操作,在“隊尾”進行插入操作。

佇列通常包括兩種操作:入佇列出佇列

C語言實現:陣列實現的佇列,並且只能儲存int資料

#include <stdio.h>
#include <malloc.h>

/**
 * C 語言: 陣列實現的佇列,只能儲存int資料。
 *
 * @author skywang
 * @date 2013/11/07
 */

// 儲存資料的陣列
static int *arr=NULL;
// 佇列的實際大小
static int count;

// 建立“佇列”
int create_array_queue(int sz) 
{
    arr = (int *)malloc(sz*sizeof(int));
    if (!arr) 
    {
        printf("arr malloc error!");
        return -1;
    }
    count = 0;

    return 0;
}

// 銷燬“佇列”
int destroy_array_queue() 
{
    if (arr) 
    {
        free(arr);
        arr = NULL;
    }

    return 0;
}

// 將val新增到佇列的末尾
void add(int val) 
{
    arr[count++] = val;
}

// 返回“佇列開頭元素”
int front() 
{
    return arr[0];
}

// 返回並刪除“佇列開頭元素”
int pop() 
{
    int i = 0;;
    int ret = arr[0];

    count--;
    while (i++<count)
        arr[i-1] = arr[i];

    return ret;
}

// 返回“佇列”的大小
int size() 
{
    return count;
}

// 返回“佇列”是否為空
int is_empty()
{
    return count==0;
}

void main() 
{
    int tmp=0;

    // 建立“佇列”
    create_array_queue(12);

    // 將10, 20, 30 依次推入佇列中
    add(10);
    add(20);
    add(30);

    // 將“佇列開頭的元素”賦值給tmp,並刪除“該元素”
    tmp = pop();
    printf("tmp=%d\n", tmp);

    // 只將“佇列開頭的元素”賦值給tmp,不刪除該元素.
    tmp = front();
    printf("tmp=%d\n", tmp);

    add(40);

    // 列印佇列
    printf("is_empty()=%d\n", is_empty());
    printf("size()=%d\n", size());
    while (!is_empty())
    {
        printf("%d\n", pop());
    }

    // 銷燬佇列
    destroy_array_queue();
}

執行結果

tmp=10
tmp=20
is_empty()=0
size()=3
30

解釋:在main函式中,先將“10.20.30”一次入佇列,佇列的資料是:10-->20-->30

下一步,通過pop()返回隊首元素,pop()操作並不會改變數列中的資料:10-->20-->30

下一步,通過front()返回並刪除隊首元素,,佇列中的資料:20-->30

最後,通過add(40)將40入佇列,佇列中的資料:20-->30-->40