[英]Basic queue implementation using linked list in C causing unexpected output
So, I have this task and I'm kind of confused because the number ( int
) that I want to print (as output) is not printed how it should.所以,我有这个任务,我有点困惑,因为我想打印(作为输出)的数字(
int
)没有打印出来。 For example: my queue contains the int
numbers 8, 9 and 10, but the numbers that show up after I run my program are 1774752, 1027013168, 1027013168. I think there's something wrong in print
module.例如:我的队列包含
int
8、9 和 10,但我运行程序后显示的数字是 1774752、1027013168、1027013168。我认为print
模块有问题。
Here's the .c
file:这是
.c
文件:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "listqueue.h"
typedef struct simpul{
Element info;
struct simpul *next;
}node;
typedef struct queue{
node *front, *rear;
} queue;
antre CreateQueue()
{
antre Q;
Q = (antre)malloc(sizeof(queue));
if (Q != NULL) // complete to alocate a new queue
{
Q->front = Q->rear = NULL;
}
return Q;
}
void enQueue(antre Q, Element X)
{
node *simpulbaru;
simpulbaru = (node *)malloc(sizeof(node));
if(simpulbaru == NULL)
{
printf("Failed to make new node");
}
simpulbaru->info = X;
simpulbaru->next = NULL;
if(Q->front == NULL)
{
Q->front = Q->rear = simpulbaru;
}
else
{
Q->rear->next = simpulbaru;
Q->rear = simpulbaru;
}
}
Element deQueue(antre Q)
{
node *hapus;
if(Q->front == NULL)
{
printf("Maaf, Antrean kosong");
}
hapus = Q->front;
Q->front = Q->front->next;
hapus->next = NULL;
free(hapus);
}
void printQ(antre Q)
{
node *tunjuk;
tunjuk = Q->front;
if(Q->front == NULL)
{
printf("Queue is empty");
}
while(tunjuk != NULL)
{
printf("%d "), tunjuk->info;
tunjuk = tunjuk->next;
}
}
Here's the .h
file:这是
.h
文件:
#ifndef _LISTQUEUE_H
#define _LISTQUEUE_H
typedef int Element;
typedef struct queue *antre;
antre CreateQueue();
void DestroyQueue(antre Q);
void enQueue(antre Q, Element X);
Element deQueue(antre Q);
void printQ(antre Q);
#include "listqueue.c"
#endif
And the main
program:和
main
程序:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "listqueue.h"
int main()
{
antre Q;
Q = CreateQueue();
enQueue(Q, 8);
enQueue(Q, 9);
enQueue(Q, 10);
printQ(Q);
return 0;
}
Issue is with your printf
statement in printQ
function.问题在于
printQ
函数中的printf
语句。
Change printf("%d "), tunjuk->info;
更改
printf("%d "), tunjuk->info;
to到
printf("%d ", tunjuk->info);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.