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