我使用嵌套結構來定義鏈表的隊列:鏈表的隊列,無端環
queue.h:
#define QUEUE_MAX_SIZE 4096
struct QUEUE_NODE {
char *string;
struct QUEUE_NODE *next;
}queue_node;
struct COMMON_QUEUE {
struct QUEUE_NODE *q_node;
}common_queue;
============= ====================
queue.c:
/* here I define the operations */
struct COMMON_QUEUE *C_init_queue() {
struct QUEUE_NODE *head;
head = malloc(sizeof(struct QUEUE_NODE));
if (head==NULL) {
fprintf(stderr, "Insufficient memory!!!");
return NULL;
}
struct COMMON_QUEUE *new_queue;
new_queue = malloc(sizeof(struct COMMON_QUEUE));
if (new_queue==NULL) {
fprintf(stderr, "Insufficient memory!!!");
return NULL;
}
head->next = NULL;
head->string = NULL;
new_queue->q_node = head;
return new_queue;
}
int C_get_queue_length(struct COMMON_QUEUE *q) {
int count;
count = 0;
while (q->q_node->next!=NULL) {
count += 1;
q->q_node = q->q_node->next;
}
return count;
}
int C_enqueue(struct COMMON_QUEUE *q, char *in) {
if (C_get_queue_length(q)>=QUEUE_MAX_SIZE) {
fprintf(stderr, "Linked queue is full!!!");
return ERROR;
}
struct QUEUE_NODE *new_node;
new_node = malloc(sizeof(struct QUEUE_NODE));
if (new_node==NULL) {
return ERROR;
}
new_node->next = NULL;
new_node->string = NULL;
while (q->q_node->next!=NULL) {
q->q_node = q->q_node->next;
}
new_node->next = q->q_node->next;
q->q_node->next = q->q_node;
new_node->string = in;
return OK;
}
,但是當我在主程序中使用它,那麼它跳轉到無盡的循環,回溯後,我知道p roblem是:
while (q->q_node->next!=NULL) {
count += 1;
q->q_node = q->q_node->next;
}
,但它似乎是正確的,但我可以讓我的兩個嵌套結構的初始化一些錯誤!
P.S.我沒有列出「免費()」。
相關:一個隊列通常有一個前/頭和尾/後。理想情況下,它也有一個長度,以消除計算長度的O(n)操作的需要(這是您的主要bug的核心,順便說一下)。 – WhozCraig
尾指針會使插入O(1)而不是O(n)。如果這個隊列比幾個條目長,這將是主要的瓶頸。 –