使用c中的链接列表进行排队

gme*_*h94 1 c queue pointers linked-list

在编译期间,此代码不会出错,但代码会突然停止.据我说,问题在于声明的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;
}
Run Code Online (Sandbox Code Playgroud)

hon*_*onk 5

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

struct queue *q;
Run Code Online (Sandbox Code Playgroud)

请注意,此处不为结构分配内存.接下来,在您的main()函数中调用:

createq(q);
Run Code Online (Sandbox Code Playgroud)

然后你在函数中访问rearfront通过:qcreateq()

q->rear=NULL;
q->front=NULL;
Run Code Online (Sandbox Code Playgroud)

这样您就可以访问未分配的内存.你应该在main()函数的开头加上类似的东西:

q = (struct queue *)malloc(sizeof(struct queue));
Run Code Online (Sandbox Code Playgroud)

并且不要忘记free(q)main()函数结束时使用以防止内存泄漏.