繁体   English   中英

使用C中的链表进行排队

[英]Queue using linked list in c

在编译过程中,该代码没有错误,但是代码突然停止。 根据我的说法,问题在于createq函数,其中声明了q->front=q->rear=NULL 它确实必须初始化。 那有什么问题吗?

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
    struct node *next;
    int data;
};

struct queue
{
    struct node *front;
    struct node *rear;
};

struct queue *q;

void createq(struct queue *);
struct queue *insert(struct queue *);
struct queue *delete_q(struct queue *);
struct queue *display(struct queue *);

int main()
{
    int option;
    printf("\tMAIN MENU\n");
    printf("\n1. Create\n2. Display\n3. Insert\n4. Delete\n5. Exit\n");
    while(option!=5)
    {
        printf("\nEnter a choice:");
        scanf("%d",&option);
        switch(option)
        {
        case 1:
            createq(q);
            break;

        case 2:
            q=display(q);
            break;

        case 3:
            q=insert(q);
            break;

        case 4:
            q=delete_q(q);
            break;
        }
    }
    return 0;
}

void createq(struct queue *q)
{
    q->rear=NULL;
    q->front=NULL;
    printf("q intialized");
}

struct queue *insert(struct queue *q)
{
    struct node *newnode;
    int val;
    newnode=(struct node *)malloc(sizeof(struct node));
    printf("Enter the value to be inserted:");
    scanf("%d",&val);
    newnode->data=val;
    if(q->front==NULL)
    {
        q->front=newnode;
        q->rear=newnode;
        q->front->next=q->rear->next=NULL;
    }
    else
    {
        q->rear->next=newnode;
        q->rear=newnode;
        q->rear->next=NULL;
    }
    return q;
}

struct queue *delete_q(struct queue *q)
{
    struct node *ptr;
    if(q->front==NULL)
    {
        printf("Queue Empty\n");
    }
    else
    {
        ptr=q->front;
        q->front=q->front->next;
        printf("Element being deleted is %d\n",ptr->data);
        free(ptr);
    }
    return q;
}

struct queue *display(struct queue *q)
{
    struct node *ptr;
    ptr=q->front;
    if(q->front==NULL)
    printf("Queue Empty!!\n");
    else
    {
        while(ptr!=q->rear)
        {
            printf("%d\t",ptr->data);
            ptr=ptr->next;
        }
        printf("%d\t",ptr->data);
            printf("\n");
    }
    return q;
}

您可以通过以下方式声明一个指向队列结构的指针:

struct queue *q;

请注意,此处未为该结构分配内存。 接下来,在main()函数中调用:

createq(q);

然后,您访问rearfront通过qcreateq()函数:

q->rear=NULL;
q->front=NULL;

这样,您可以访问未分配的内存。 您应该在main()函数的开头放置以下内容:

q = (struct queue *)malloc(sizeof(struct queue));

并且不要忘记在您的main()函数的末尾放置free(q)以防止内存泄漏。

您正在将类型为struct queue *指针q传递给该函数。 但是您尚未为该指针分配内存。

因此,您需要将内存分配给指针q ,然后传递给函数。 您需要像这样分配内存

q = (struct queue *)malloc(sizeof(struct queue));

然后将q传递给您的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM