【发布时间】:2019-11-02 08:24:27
【问题描述】:
使用 C 实现队列 ADT 的程序
在 .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 结构的情况下运行代码时(基本上这意味着在 queue.c 文件中声明一个静态类型的 *head 和 *tail 指针,它一次只允许创建一个队列。因此CreateQueue 函数将是 void 类型,而其他函数不需要 Queue 类型的参数**)) 它运行时没有任何错误。
【问题讨论】:
-
通过 valgrind 运行此程序可能有助于确定错误原因
-
在 create_Queue 中,您永远不会为队列分配内存。
-
@L0neGamer 感谢您的支持;我在 valgrind.org 上查看了它,我绝对想试试这个。目前我在 Windows(默认)上,当我切换到我的 Linux 子系统时,我将使用 valgrind 尝试它
-
@Nico238你不需要在create_queue()中分配内存