Я пытался создать ADT очереди в C, но что-то не так в моем коде ... Кто-нибудь может это исправить? - PullRequest
0 голосов
/ 02 ноября 2019

Программа для реализации ADT очереди с использованием C

Объявление заголовков в файле .c или заголовочном файле ничего не меняет в ошибках

1) ЗаголовокФайл (queue.h)

#ifndef QUEUE
#define QUEUE
#include <stdio.h>
#include <stdlib.h>

typedef struct QNodeType
{
    char ch;
    struct QNodeType *next;
}QNode;

typedef struct QueueType
{
    QNode *head,*tail;
}Queue;

Queue **Create_Queue();                // Initialize the queue
void ClearQueue();               // Remove all items from the queue
int Enqueue(Queue **q,char ch);            // Enter an item in the queue
char Dequeue(Queue **q);                  // Remove an item from the queue
int isEmpty(Queue **q);                   // Return true if queue is empty
int isFull(Queue **q);                    // Return true if queue is full

// Define TRUE and FALSE if they have not already been defined
#ifndef FALSE
#define FALSE (0)
#endif
#ifndef TRUE
#define TRUE (!FALSE)
#endif

#endif 

2) .c Файл для определения функций очереди


#include "queue.h"

Queue** Create_Queue()
{
    Queue **q;
    (*q)->head = (*q)->tail = NULL;
    return q;
}

void ClearQueue(Queue **q)
{
    QNode *temp;
    while((*q)->head != NULL)
    {
        temp = (*q)->head;
        (*q)->head = (*q)->head->next;
        free(temp);
    }

    (*q)->head = (*q)->tail = NULL; // Reset indices to start over
}

int Enqueue(Queue **q,char ch)
{
    QNode *temp;


    if(isFull(q)) return FALSE;

    temp = (QNode *)malloc(sizeof(QNode));
    temp->ch = ch;
    temp->next = NULL;

    if((*q)->head == NULL)
        (*q)->head = (*q)->tail = temp;
    else
    {
        (*q)->tail->next = temp;        // Insert into the queue
        (*q)->tail = temp;              // Set tail to new last node
    }

    return TRUE;
}
char Dequeue(Queue **q)
{
    char ch;
    QNode *temp;

    if(isEmpty(q)) return '\0'; 
    else
    {
        ch = (*q)->head->ch;        
        temp = (*q)->head;
        (*q)->head = (*q)->head->next;    
        free(temp);            

        if(isEmpty(q))
        {
            (*q)->head = (*q)->tail = NULL;        
        }
    }
    return ch;               
}        
int isEmpty(Queue **q)
{
    return ((*q)->head == NULL);
}

int isFull(Queue **q)
{
    return FALSE;
}   

3) Драйвер программы или основнойкод

#include "queue.h"

int main()
{
    char testString[27];
    int i;
    char ch;
    Queue **q=Create_Queue();

    Enqueue(q,'A');
    printf("Enqueued: %c\n", Dequeue(q));

    strcpy(testString, "abcdefghijklmnopqrasuvwxyz"); 

    i = 0;
    printf("Testing enqueuing of string: %s\n", testString);
    while(testString[i] != '\0')
    {
        if(!Enqueue(q,testString[i]))
        {
            printf("Queue is full. Unable to enqueue %c\n", testString[i]);
        }
        i++;
    }

    printf("Dequeued letters are...\n");
    while((ch = Dequeue(q)) != '\0') // Dequeue returns null terminator 
        printf("%c", ch);            // when queue is empty

    printf("\nEnd of queue encountered...\n");
    return 0;
}


Приведенная выше программа показывает ошибку сегментации при запуске в Linux и произвольное возвращаемое значение при запуске на dev c ++ .


Но когда я запускаю код без структуры QUEUE (, в основном это означает объявление * head и * tail указателя статического типа в файле queue.c, который допускает только одиночередь, создаваемая за раз. Таким образом, функция CreateQueue будет иметь тип void, а другим функциям не требуется аргумент типа Queue **) ), она выполнялась без ошибок.

1 Ответ

0 голосов
/ 02 ноября 2019

Я думаю, что проблема в create_Queue (), вы не выделяете в нем никакой памяти, после этого в void ClearQueue () вы используете free ().

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