2014-10-09 121 views
3

我有一個基本的隊列設計,但我想要有多個隊列。現在看來,我需要另一個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]

+0

對於推式符號'iceCreamLine.push(13);'來說,你需要在'struct Node'結構中有一個元素'void(* push)(int);',你必須確保每個'struct Node'都被正確初始化,以便'push'元素指向正確的函數。 – 2014-10-09 18:41:34

+0

使用'head'和'tail'等不同名稱創建文件的新版本將是一場災難。 +1在執行前儘可能多地懷疑和困擾。 – 2014-10-09 18:44:31

回答

3
struct Queue { 
    struct Node *head, *tail; 
}; 

添加QueueInit函數分配並初始化一個隊列,返回一個指向struct Queue的指針。通過指針struct Queuepushpop,並擺脫您的全球headtail

+0

我編輯了上面的代碼,但我不是從C背景。頭部和尾部會初始化到什麼程度?推動和流行怎麼知道頭部和尾部是什麼?謝謝 – user3838436 2014-10-09 19:28:58

+0

根據你的其他代碼,你可以將'head'和'tail'初始化爲'NULL'。你可以在push和pop的參數列表中添加一個'struct Queue *' - void push(struct Queue * myQueue,int x)''和'void pop(struct Queue * myQueue)'。在'push'和'pop'中,你可以參考'myQueue-> head'和'myQueue-> tail'。另外,你的'QueueInit'應該有一個'return thisQueue;'。 – 2014-10-09 19:44:17

+0

謝謝,我想我差不多有它的工作。我確實需要像iceCreamLine.push(13)這樣的語法;而不是推(&iceCreamLine,13),但那樣做。我編輯了你所說的代碼,但在我的第二個printf上得到了警告和分段轉儲。我來討厭指針! – user3838436 2014-10-09 21:05:15