【发布时间】:2020-03-24 18:26:33
【问题描述】:
我使用链接实现在 C 语言中尝试了一个基本的队列程序。但它显示了用于将元素插入队列的函数的一些错误。我也想显示队列中的元素。下面是我试过的代码。当编译器进入我用来插入元素的 Insert() 函数时,CLI 退出。另外我想确保我用来显示元素的方法是对还是错。
#include<stdio.h>
#include<stdlib.h>
typedef int QueueElement;
typedef enum{FALSE,TRUE} Boolean;
typedef struct node{
QueueElement data;
struct node *next;
}Node;
typedef struct queue{
Node *rear;
Node *front;
Boolean Full;
int count;
}Queue;
void CreateQueue(Queue *q){
q->count = 0;
q->Full = FALSE;
q->front = q->rear = NULL;
}
Boolean IsQueueEmpty(Queue *q){
return(q->front == NULL && q->rear == NULL);
}
Boolean IsQueueFull(Queue *q){
return(q->Full);
}
void Insert(QueueElement x, Queue *q){
Node *np;
np = (Node* )malloc(sizeof(Node));
if(np == NULL){
printf("Memory is Full\n");
q->Full = TRUE;
}
np->data = x;
np->next = NULL;
if(IsQueueEmpty(q))
q->front = q->rear = np;
else{
q->rear->next = np;
q->rear = np;
}
q->count++;
}
void Remove(QueueElement *x, Queue *q){
Node *np;
if(IsQueueEmpty(q))
printf("Queue is Empty\n");
else{
q->count--;
*x = q->front->data;
np = q->front;
q->front = q->front->next;
if(q->front == NULL)
q->rear = NULL;
free(np);
}
}
int main(){
Queue q;
Insert(21,&q);
int n;
Remove(&n,&q);
printf("%d ",n);
}
【问题讨论】:
标签: c data-structures linked-list queue