我有一個基本的隊列設計,但我想要有多個隊列。現在看來,我需要另一個queue.h文件,並用不同的名稱替換頭尾,但我確定有更好的方法?C中的多個隊列
queue.h *編輯
#include<stdlib.h> // malloc
struct Node {
int data;
struct Node* next;
};
struct Queue {
struct Node *head, *tail;
};
struct Queue *QueueInit() {
//allocate and initialize a queue
struct Queue *thisQueue = malloc(sizeof *thisQueue);
thisQueue->head = NULL;
thisQueue->tail = NULL;
return thisQueue;
}
void push(struct Queue *myQueue, int x) {
struct Node *temp;
temp = malloc(sizeof(struct Node));
temp->data = x;
temp->next = NULL;
if(myQueue->head == NULL && myQueue->tail == NULL) { //empty
myQueue->head = myQueue->tail = temp;
return;
}
myQueue->tail->next = temp;
myQueue->tail = temp;
}
void pop(struct Queue *myQueue) {
struct Node* temp = myQueue->head;
if(myQueue->head == NULL) return; //empty
if(myQueue->head == myQueue->tail) {
myQueue->head = myQueue->tail = NULL;
}
else {
myQueue->head = myQueue->head->next;
}
free(temp);
}
如何創建多個隊列這樣嗎?
的main.c
int main() {
struct Node iceCreamLine;
struct Node bathroomLine;
iceCreamLine.push(13);
bathroomLine.push(2);
//It looks like I will have to use this syntax then instead?
struct Queue *droneQueue; //(THIS IS LINE 5)
push(&droneQueue,1666);
push(&droneQueue,100);
printf("--> %d",&droneQueue->head->data);
printf("--> %d",&droneQueue->head->next->data);
}
第一個printf的作品,但第二個給我一個分割轉儲。這裏是警告
main.c:函數'main': main.c:6:2:warning:從不兼容的指針類型[默認啓用]傳遞'push'的參數1 包含的文件from queue.c:2:0: queue.h:21:6:note:expected'struct Queue *'but argument is of type'struct Queue **' main.c:7:2:warning:passing argument從不兼容的指針類型'推''默認啓用] 從queue.c中包含的文件:2:0: queue.h:21:6:note:expected'struct Queue *'但參數類型爲'結構隊列**' main.c:9:2:warning:格式'%d'需要類型'int'的參數,但參數2的類型爲'int *'[-Wformat] main.c中:10:2:警告:格式 '%d' 期望類型的 'INT' 參數,但參數2具有輸入 'INT *'[-Wformat]
對於推式符號'iceCreamLine.push(13);'來說,你需要在'struct Node'結構中有一個元素'void(* push)(int);',你必須確保每個'struct Node'都被正確初始化,以便'push'元素指向正確的函數。 – 2014-10-09 18:41:34
使用'head'和'tail'等不同名稱創建文件的新版本將是一場災難。 +1在執行前儘可能多地懷疑和困擾。 – 2014-10-09 18:44:31