數據結構手把手教學——循環隊列

一、隊列

1、隊列特點:

①、線性結構、具有隊頭和隊尾,有且只有一個直接前驅和直接後繼。
②、只允許在一段插入(入隊)、另一端刪除(出隊),且先進先出


二、循環隊列

順序隊列是隊列得順序存儲結構,通過改進後成爲循環隊列。

在這裏插入圖片描述

1、規定

①、front表示隊頭得前一個位置下標。
②、rear表示隊尾位置下標。
③、隊列空時:front = rear

2、改進後循環隊列

在這裏插入圖片描述


三、用C語言實現順序隊列

1、構造存儲結構
#define SIZE 8
typedef int datatype;
typedef struct seqqueue
{
    datatype data[SIZE];   // 數據域
    int front;  // 隊頭前一個位置下標
    int rear;   // 隊尾位置下標
}seq_queue, *seq_pqueue;
2、初始化

①申請內存空間
②front = rear = SIZE - 1

void init_seqqueue(seq_pqueue *queue)
{
    (*queue) = (seq_pqueue)malloc(sizeof(seq_queue));

    if (NULL == (*queue))
    {
        perror("malloc");
        exit(1);
    }

    (*queue)->front = SIZE - 1;
    (*queue)->rear = SIZE - 1;
}
3、入隊

①、改進前入隊方式

rear++;
data[rear] = dat;

假設設定得隊列SIZE = 8,我們知道初始化得時候rear = -1,當rear++7的時候就已經入隊滿了,如果此時有人出隊,再想入隊,rear++會等於8,溢出不能入隊。
在這裏插入圖片描述

②、改進的入隊方式

rear = (rear + 1) % SIZE;
data[rear] = dat;

③、入隊前先判斷隊列是否已滿

判斷front = (rear + 1)%SIZE;是否成立。

bool isfull_seqqueue(seq_pqueue queue)
{
    if (queue->front == (queue->rear + 1) % SIZE)
    {
        return true;
    }
    else
    {
        return false;
    }
}

④、入隊實現代碼

void in_seqqueue(seq_pqueue queue, datatype dat)
{
    if (isfull_seqqueue(queue))
    {
        printf("隊列已滿\n");
        return;
    }
    
    queue->rear = (queue->rear + 1) % SIZE;
    queue->data[queue->rear] = dat;
}
4、出隊

根據前面入隊分析,同理可以知道入隊方式:
front = (front + 1)%SIZE;
*dat = data[front];

①、出隊前先判斷隊列是否已空。

front = rear的時候表示隊列已空。

bool isempty_seqqueue(seq_pqueue queue)
{
    if (queue->front == queue->rear)
    {
        return true;
    }
    else
    {
        return false;
    }
}

②、出隊實現代碼

void out_seqqueue(seq_pqueue queue, datatype *dat)
{
    if (isempty_seqqueue(queue))
    {
        printf("隊列已空\n");
        return;
    }

    queue->front = (queue->front + 1) % SIZE;
    *dat = queue->data[queue->front];
}
5、打印
void show_seqqueue(seq_pqueue queue)
{
    int i = 0;

    for (i = (queue->front + 1) % SIZE; i != (queue->rear + 1) % SIZE; i = (i + 1) % SIZE)
    {
        printf("%d\t", queue->data[i]);
    }

    printf("\n");
}

四、練習題

用戶從鍵盤輸入整數,程序將其入隊,用戶輸入字母,程序將隊頭元素出隊,並在每一次出隊和入隊之後打印隊列元素。

1、實現代碼
int main(void)
{
    seq_pqueue queue = NULL;
    datatype in_data = 0;
    datatype out_data = 0;
    int ret = 0;

    init_seqqueue(&queue);  // 初始化隊列

    while (1)
    {
        printf("輸入整數:");
        ret = scanf("%d", &in_data);

        if (ret != 0)
        {
            in_seqqueue(queue, in_data);
            printf("入隊後隊列元素:");
            show_seqqueue(queue);
        }
        else
        {
            out_seqqueue(queue, &out_data);
            printf("出隊後隊列元素:");
            show_seqqueue(queue);
            while(getchar() != '\n');   // 清空輸入緩衝
        }
    }

    return 0;
}
2、結果

在這裏插入圖片描述


五、完整代碼

https://github.com/sanjaywu/DataStructure

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章