【问题标题】:What am I doing wrong in my pop function (queue) C我在弹出函数(队列)C 中做错了什么
【发布时间】:2013-02-28 03:11:09
【问题描述】:

我必须编写一个程序来实现一个带有各种菜单选项的队列(这些都已完成)。我的“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);
}

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

【问题讨论】:

  • 您还没有向我们展示程序状态是什么。您的程序将根据数据表现不同。我现在可以告诉你,如果你最终搜索队列,你并没有正确地从列表中取消链接。您也可以直接在列表末尾进行搜索。我也不明白你在函数结束时修改tail 的动机,但它看起来很可疑。

标签: c linked-list queue


【解决方案1】:

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

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

最后,也许您可​​能想要考虑从弹出窗口中返回 data(如果有),以及一个布尔条件 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);
    }
}

【讨论】:

  • 终于!!!谢谢你。我忘记将前一个节点链接到正在删除的节点之后的下一个节点......非常感谢!我在这个项目上花了很长时间,完成它只是一种解脱。我很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2015-11-19
  • 2011-04-15
  • 1970-01-01
相关资源
最近更新 更多