Реализация очереди Basi c с использованием связанного списка в C, вызывающего неожиданный вывод - PullRequest
0 голосов
/ 30 марта 2020

Итак, у меня есть эта задача, и я немного запутался, потому что число (int), которое я хочу напечатать (как вывод), напечатано не так, как должно. Например: моя очередь содержит int числа 8, 9 и 10, но числа, которые отображаются после запуска моей программы, - 1774752, 1027013168, 1027013168. Я думаю, что в модуле print что-то не так.

Вот файл .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;
  }

}

Вот файл .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

И программа 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;
 }

1 Ответ

2 голосов
/ 30 марта 2020

Проблема связана с вашим оператором printf в функции printQ.

Измените printf("%d "), tunjuk->info; на

printf("%d ", tunjuk->info);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...