c - C 中的队列,错误的打印

标签 c queue

非常感谢堆栈方面的帮助,现在我已经自己编写了队列..但是我只有一个问题。当我只添加一个项目并且我想打印它时,程序会无限打印这个数字。我的推送/打印功能有什么问题?

#include <stdio.h>
#include <stdlib.h>
typedef struct Element Element;
typedef struct Element
{
    int value;
    Element* next;
} Element;

Element* first = NULL;
Element* last = NULL;

void pop();
void push(int x);
void printqueue();

int main()
{
    int x;
    int warunek;
    do
    {
        printf("\nMENU\n");
        printf("1. Push[1]\n2. Pop[2]\n3. Print[3]\n0. Wyjdz[0]\n");
        printf("Podaj warunek: ");
        scanf("%d", &warunek);
        switch(warunek)
        {
            case 1:
            {
                printf("Give a number: ");
                scanf("%d", &x);
                push(x);
            }
            break;
            case 2: pop();
            break;
            case 3: printqueue();
            break;
            default: printf("Bad value.\n");
        }
    }
    while(warunek != 0);
    return 0;
}

void push(int x)
{
    Element* pNewItem = (Element*)malloc(sizeof(Element));
    pNewItem->value = x;
    pNewItem->next = NULL;
    if(first == NULL && last == NULL)
    {
        first = last = pNewItem;
    }
    last->next = pNewItem;
    last = pNewItem;
}

void pop()
{
    Element* pNewItem = first;
    if(first == NULL)
        printf("Queue is empty.\n");
    else if(first == last)
        first = last = NULL;
    else
        first = first->next;
    free(pNewItem);
}


void printqueue()
{
    Element* temp = first;
    printf("\nContent of queue\n");
    while(temp != NULL)
    {
        printf("%d\n", temp->value);
        temp = temp->next;
    }
    printf("\n");
}

最佳答案

我猜是这一行:

last->next = pNewItem;

first == last 时,您在此处创建一个循环 -> 将其放在 else 分支中。

关于c - C 中的队列,错误的打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43871450/

相关文章:

c - 在头文件的声明中定义结构的值

python - 什么时候需要 Queue.join() ?

Javascript:如何使用单个数组实现三个堆栈?

mysql - 以编程方式登录mysql

c - 我是否需要在 make 文件的依赖项列表中包含其他头文件中包含的头文件?

c - 有符号字符的无符号字符输出

java - 为什么我在 Mule 中使用 JMS 队列后没有得到更改的有效负载?

c# - asp.net core 中的队列任务

ruby-on-rails - 使用 sidekiq 处理两个单独的 redis 实例?

c - 在 GCC 编译中隐藏函数名称