【问题标题】:two queues one program两个队列一个程序
【发布时间】:2018-01-20 08:18:33
【问题描述】:

我想在银行创建两个普通客户和贵宾客户队列, 1.如何在一个程序中创建两个队列。 2.如何将队列的结构作为函数入队和出队的参数传递? 我正在根据客户类型进行查询,例如 如果客户端是 vip,我会加入 queue1 如果客户端是普通的,我会加入 queue2 出队也一样

#include <stdio.h>
#include <malloc.h>
#include<string.h>

int position=0;
int length=1;enter code here

typedef struct Node
{
    int record;
    int CardNum;
    char CustomerType[20];
    struct Node* next;

}Node;

//VIP QUEUE
typedef struct queue
{
    Node* front1 = NULL;
    Node* rear1 = NULL;
}Queue1;

//Ordinary QUEUE
typedef struct queue
{
    Node* front2 = NULL;
    Node* rear2 = NULL;
}Queue2;

void Enqueue();
void Dequeue();

int main()
{
    char command[10];
    while(scanf("%s",command))
    {
        if(strcmp(command,"IN") == 0)
        {
            printf("IN:");
            Enqueue();
        }
        if(strcmp(command,"LIST") == 0)
        {
            printf("LIST:\n");
            List();
        }
        if(strcmp(command,"OUT") == 0)
        {
            Dequeue();
        }
        if(strcmp(command,"QUIT") ==0)
        {
            printf("GOOD BYE!\n");
            break;
        }
    }
    return 0;
}

【问题讨论】:

  • 您尝试了什么,遇到了什么问题?另外,为什么队列需要两种不同的类型?它们应该是相同的类型,因为没有区别。

标签: c struct queue


【解决方案1】:

问题是您创建了两种不同的Queue 类型。但事实并非如此。毕竟,我们用来存储 VIP 的所有队列将与另一个队列的类型相同。但是是的,您需要该队列类型的两个不同实例

此外,您不能在 struct 声明中初始化成员。这行不通。

Queue 传递给另一个函数有几种方法。您可以简单地创建Queue q1,q2,然后将其地址传递给函数以分配必要的节点。

typedef struct queue
{
    Node* front;
    Node* rear;
}Queue;

Queue q1,q2;
init(&q1);
init(&q2);
...

void init(Queue *q1){
    q1->front = NULL;
    q2->rear  = NULL;
}

init 的签名是

void init(Queue *q);

无论我在init 中显示的内容,您都可以对其他队列函数执行相同的操作。

事实上,你可以不传递地址,然后对传递给函数的本地结构实例进行更改,然后返回它。

我不能忽视的其他几点:

您已使用 scanf 并以一种方式检查了它的返回值 - 以正确的方式进行。

while(scanf("%9s",command) == 1){
   ...

另外一点是在相同条件下使用多个if。您应该合并 if 语句 - 使您免于重复代码,而且您没有进行冗余检查。


您也可以像这样初始化结构(但我展示了另一种方式,以便您可以编写其他队列函数)。

Queue q1 = { .front = NULL, .rear = NULL };

另外,main 的签名应该是 int main(void)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多