資料結構迴圈佇列的自動擴充容量
阿新 • • 發佈:2018-11-16
迴圈佇列的基本操作及自動擴容
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int QElemType;
typedef int Status;
1.初始化佇列
Status InitQueue(SqQueue * Q) { Q->queue_size = MAX_QUEUE_SIZE; Q->base = malloc(Q->queue_size * sizeof(SqQueue)); if (!Q->base) return ERROR; Q->font = 0; Q->rear = 0; return OK; }
2.入隊操作
當rear的標號大於font的標號時,這時候擴容是非常簡單的,直接使font+1即可
但是由於是迴圈佇列,所以會出現rear的標號小於font的標號,此時如果直接將rear的標號+1,那麼rear==font 這時候就會出現問題,
那麼如何解決rear小於font這種情況呢
基本想法是這樣的:將佇列中的元素放到一個新的陣列中,然後將陣列的元素賦值給佇列的頭指標指向的陣列,然後再將插入的元素放到這個佇列中,這樣佇列就被重置為font大於rear的情況了,對於黑盒外的使用者而言只需要看到佇列的特點(放入元素在隊尾,刪除元素在對頭)即可。
程式碼如下:
Status EnQueue(SqQueue * Q, QElemType e) { if (!Q) return ERROR; if ((Q->rear + 1) % Q->queue_size == Q->font) { Q->queue_size = Q->queue_size + INCREMENT_SIZE; Q->base = realloc(Q->base, sizeof(QElemType) * Q->queue_size); if (!Q->base) return ERROR; if (Q->rear < Q->font) { int i = Q->font; int j = 0; int temp_A[Q->queue_size]; // hold the value of the queue for (i; i != Q->rear; j++) { temp_A[j] = Q->base[i]; i = (i + 1) % (Q->queue_size - INCREMENT_SIZE); } // put the value of the array to the queue Q for (int k = 0; k < (Q->queue_size-1-INCREMENT_SIZE); k++) { Q->base[k] = temp_A[k]; printf("Q: %d A: %d \n", Q->base[k], temp_A[k]); } // put the new elem to the queue Q->base[Q->queue_size-1-INCREMENT_SIZE] = e; Q->font = 0; Q->rear = Q->queue_size-1; return OK; } } Q->base[Q->rear] = e; Q->rear = (Q->rear+1) % Q->queue_size; return OK; }
3.出隊操作
Status DeQueue(SqQueue * Q, QElemType * e) { if (!Q || (Q->font == Q->rear)) return ERROR; *e = Q->base[Q->font]; Q->font = (Q->font + 1) % Q->queue_size; return OK; } // If the queue is empty return true else return false Status QueueEmpty(SqQueue * Q) { if (Q->font == Q->rear) return TRUE; else return FALSE; }
4.列印佇列
Status printQueue(SqQueue * Q)
{
int status = TRUE;
if (!Q || (Q->font == Q->rear))
status = FALSE;
int index = Q->font;
int i = Q->font;
while ( i % Q->queue_size != Q->rear)
{
// printf(" array[%d] num %d \n", i, Q->base[index]); // 這裡應該使用vist函式的,提高通用性
printf("\t num %d \n", Q->base[index]); // 這裡應該使用vist函式的,提高通用性
i++;
index = (i) % Q->queue_size ;
}
return status;
}
PS:轉載請註明出處!!!