C中的多个队列

时间:2014-10-09 18:19:45

标签: c queue

我有一个基本的队列设计,但我希望有多个队列。它现在的样子是我需要另一个queue.h文件并用不同的名字替换head和tail,但我相信还有更好的方法吗?

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:警告:从不兼容的指针类型[默认启用]传递'push'的参数1 在queue.c:2:0中包含的文件中: queue.h:21:6:注意:预期'struct Queue *'但参数类型为'struct Queue **' main.c:7:2:警告:从不兼容的指针类型[默认启用]传递'push'的参数1 在queue.c:2:0中包含的文件中: queue.h:21:6:注意:预期'struct Queue *'但参数类型为'struct Queue **' main.c:9:2:警告:格式'%d'需要类型为'int'的参数,但参数2的类型为'int *'[-Wformat] main.c:10:2:警告:格式'%d'需要类型为'int'的参数,但参数2的类型为'int *'[-Wformat]

1 个答案:

答案 0 :(得分:3)

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

添加QueueInit函数来分配和初始化队列,返回指向struct Queue的指针。将指针struct Queue传递给pushpop,然后摆脱全局headtail