【问题标题】:unknown coding error in implementation of queue using linked list使用链表实现队列时出现未知编码错误
【发布时间】:2012-12-29 11:22:52
【问题描述】:

以下是我使用链表实现队列。我对数据结构完全陌生 并试图实现队列数据结构。这段代码编译成功,但是一旦我尝试运行它,程序就会崩溃。我不知道如何解决这个问题。如果你们有任何线索,我的代码有什么问题,请给我一个想法。

感谢您的帮助。

这是我的 C 代码:

#include<stdio.h>
#include<stdlib.h>
#define null 0
typedef struct node//node of a linked list
{
    int info;//info part of node
    struct node* next;// next pointer of a node
}*nodeptr;
typedef struct queue
{
    nodeptr front;//front pointer of a queue
    nodeptr rear;//rear pointer of a queue
} *QUEUE;

int empty_queue(QUEUE qwe)//if queue is empty then return 1
{
    if (qwe->front==null)
    return 1;
    else
    return 0;
}
void insert_queue( QUEUE qwe,int x)
{
    nodeptr p=(nodeptr)malloc(sizeof(struct node));//allocate new memory space to be added to queue
    p->next=null;
    p->info=x;
    if(empty_queue(qwe))//if the queue is empty,front and rear point to the new node
    {
    qwe->rear=p;
    qwe->front=p;
    return; 

    }
    qwe->rear->next=p;
    qwe->rear=p;
    //rear points to the new node
    return; 
}
int delete_queue(QUEUE qwe)
{   
    int x;
    if(empty_queue(qwe))//if queue is empty then it is the condition for underflow
    {
        printf("underflow\n");
        return;
    }
    nodeptr p=qwe->front;//p points to node to be deleted
    x=p->info;//x is the info to be returned
    qwe->front=p->next;
    if(qwe->front==null)//if the single element present was deleted
    qwe->rear=null;
    free(p);
    return x;

}
int main()
{
    int a;
    QUEUE qwe;
    qwe->rear=null;
    qwe->front=null;
    printf("enter values to be enqueued and -1 to exit\n");
    while(1)
    {
        scanf("%d",&a);
        if(a==-1)
        break;
        insert_queue(qwe,a);
    }
    printf("the values you added to queue are\n");
    while(!empty_queue(qwe))
    printf("%d\n",delete_queue(qwe));
    return 0;


}

【问题讨论】:

    标签: c algorithm data-structures queue


    【解决方案1】:

    QUEUE qwe; 声明了一个指向未初始化内存的指针。您需要在堆栈上为队列分配内存

    struct queue qwe
    qwe.rear=null;
    

    或在堆上动态

    QUEUE qwe = malloc(sizeof(*qwe));
    qwe->rear=null;
    ...
    free(qwe); /* each call to malloc requires a corresponding free */
    

    当你在 typedef 后面隐藏一个指针时,很容易引入这种类型的 buf。另一种解决方案是将QUEUE 更改为struct queue 类型。这样您就更有可能注意到代码中任何未初始化的指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多