I have a basic queue design, but I want to have multiple queues. The way it looks right now is that I would need another queue.h file and replace head and tail with different names, but I am sure there is a better way?
queue.h *Edited
#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);
}
How can I create multiple queues like this?
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);
}
The first printf works, but the second one gives me a segmentation dump. Also here are the warnings
main.c: In function ‘main’: main.c:6:2: warning: passing argument 1 of ‘push’ from incompatible pointer type [enabled by default] In file included 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 1 of ‘push’ from incompatible pointer type [enabled by default] In file included from queue.c:2:0: queue.h:21:6: note: expected ‘struct Queue *’ but argument is of type ‘struct Queue **’ main.c:9:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat] main.c:10:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]
struct Queue {
struct Node *head, *tail;
};
Add a QueueInit
function to allocate and initialize a queue, returning a pointer to a struct Queue
. Pass a pointer to struct Queue
to push
and pop
, and get rid of your global head
and tail
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments