【问题标题】:How to insert an element in Queue in c using linked implementation如何使用链接实现在 c 中的队列中插入元素
【发布时间】: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


    【解决方案1】:
    Queue q;
    Insert(21,&q);
    

    在声明q 之后,你应该调用createQueue 函数来初始化count, rear and front 指针。

     Queue q;
     CreateQueue(&q);
     Insert(21,&q);
    

    否则它们将具有不确定的值。


    显示队列的功能。

    void Display(Queue q) {
      Node *iter = q.front;
    
       while(iter) {
          printf("%d ", iter->data);
          iter = iter->next;
       }   
    }
    

    main调用如下。

    Display(q);
    

    【讨论】:

    • 是的,我犯了那个愚蠢的错误..还有其他方法可以使用链表显示队列中的元素
    猜你喜欢
    • 1970-01-01
    • 2010-12-11
    • 2021-07-24
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2011-06-28
    • 2020-04-17
    • 1970-01-01
    相关资源
    最近更新 更多