C语言中的多队列
我有一个基本的队列设计,但我想有多个队列。现在看来,我需要另一个queue.h文件,并用不同的名称替换head和tail,但我确信有更好的方法吗 queue.h*已编辑C语言中的多队列,c,queue,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()
#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);
}
第一个printf可以工作,但是第二个printf给了我一个分段转储。这里还有警告
main.c:在函数“main”中:
main.c:6:2:警告:从不兼容的指针类型传递“push”的参数1[默认情况下已启用]
在队列中包含的文件中。c:2:0:
queue.h:21:6:注意:应为“struct queue*”,但参数的类型为“struct queue**”
main.c:7:2:警告:从不兼容的指针类型传递“push”的参数1[默认情况下已启用]
在队列中包含的文件中。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]
struct Queue {
struct Node *head, *tail;
};
添加
QueueInit
函数来分配和初始化队列,返回指向struct队列的指针。将指向struct Queue
的指针传递给push
和pop
,并去掉推式符号iceCreamLine.push(13)的全局头和尾代码>要工作,需要一个元素void(*push)(int)在struct节点
结构中,您必须确保每个struct节点
都已正确初始化,以便push
元素指向正确的函数。为head
和tail
等创建具有不同名称的文件的新版本将是一场灾难+我在上面编辑了我的代码,但我不是C语言背景。头和尾巴会得到什么?“推”和“砰”怎么知道“头”和“尾”是什么?谢谢基于您的其他代码,您将初始化head
和tail
到NULL
。您可以将一个struct Queue*
添加到push和pop的参数列表中-void push(struct Queue*myQueue,int x)
和void pop(struct Queue*myQueue)
。在push
和pop
中,您可以参考myQueue->head
和myQueue->tail
。另外,您的QueueInit
应该有一个返回此队列代码>。谢谢,我想我差不多可以用了。我确实想要像iceCreamLine.push(13)这样的语法;而不是推(&iceCreamLine,13),但这样就可以了。我按照大家所说的对代码进行了编辑,但在第二次printf中得到了警告和分段转储。我开始讨厌指针了!当您将队列
声明为指针时,不应使用&
将其发送到推送
&droneQueue
表示指向droneQueue
的指针,因此,在对其进行编码时,是指向指针的指针。摆脱所有的&
应该会有所帮助。另外,不要忘记初始化队列
,方法是将QueueInit的返回值赋值给它。
struct Queue {
struct Node *head, *tail;
};