1

我必须编写一个程序来实现一个带有各种菜单选项的队列(这些都完成了)。我的“pop”功能有问题。

我的计划是员工餐厅候补名单。每当顾客打电话或进入餐厅时,他们都会被列入等候名单。弹出(就座)的唯一方法是客户的状态是在餐厅等候。我已经正确编写了将客户从呼入到在餐厅等候的部分。

此外,如果组大小大于桌子大小,我应该去下一个节点并检查下一个组是否符合就座标准。

enum status(WAIT,CALL);

typedef struct restaurant
{
//stuff
}list;

//I call pop in the main as follows:

pop(&head, &tail);   

void pop(list** head, list** tail)
{
    list* temp = *head;
    int tableSize;

    if(*head == *tail && *tail == NULL)
    {
        printf("The queue is empty... exitting program... \n");
        exit(EXIT_FAILURE);
    }

    printf("What is the table size? ");
    scanf(" %d", &tableSize);

    if(temp->groupSize > tableSize || temp->waitStatus == CALL)
        while(temp->groupSize > tableSize || temp->waitStatus == CALL)
            temp = temp->nextNode;

    else
        *head = (*head)->nextNode;

    if(*tail == temp)
        *tail = (*tail)->nextNode;

    free(temp);
}

当我显示我的输出时,如果它必须跳过队列中的第一个人,它不会删除实例中的节点。但是,当第一个人符合标准时,它确实有效。为什么是这样?

4

1 回答 1

2

首先,您的 pop 似乎允许删除列表中间的项目。虽然这是可行的,但它要求您记住指向弹出节点的内容,以确保将其设置为弹出节点之后的节点。有很多方法可以做到这一点。

此外,您的 empty() 条件已关闭。head如果列表为空,则将始终为 NULL,前提是您正确地将新添加的节点nextNode成员设置为 NULL。不需要对 NULL进行比较tail或检查。tail

最后,也许您可​​能需要考虑从弹出窗口中返回数据(如果有的话),并将布尔条件 true/false 作为函数返回结果来指示是否有东西被取出。否则,您的程序如何知道数据已成功检索,以及该数据什么?

无论如何,只需使用您当前删除匹配内容的口头禅:

void pop(list** head, list** tail)
{
    list *temp = NULL, *prior = NULL;
    int tableSize = 0;

    if(*head == NULL)
    {
        printf("The queue is empty... exitting program... \n");
        exit(EXIT_FAILURE);
    }

    printf("What is the table size? ");
    scanf(" %d", &tableSize);

    temp = *head;
    while (temp && (temp->groupSize > tableSize || temp->waitStatus == CALL))
    {
        prior = temp;
        temp = temp->nextNode;
    }

    if (temp)
    {
        // only way prior is set is if temp is NOT
        //  pointing to the first node, therefore *head
        //  is not changed.
        if (prior)
        {
            prior->nextNode = temp->nextNode;

            // if we made it to the tail ptr, then it needs
            //  to be moved back to the prior node
            if (*tail == temp)
                *tail = prior;
        }
        else
        {   // first node was removed. so move head to
            //  the next node (which may be NULL)
            *head = temp->nextNode;
        }

        // release the node
        free(temp);
    }
}
于 2013-02-28T03:23:56.840 回答