2014-10-08 73 views
1

在编译过程中,此代码没有提供任何错误,但代码突然停止。根据我的问题是createq函数,其中q->front=q->rear=NULL宣布。它必须被初始化。有什么不对吗?在c中使用链接列表的队列

#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; 
} 
+2

代码“停止”在哪里?是否存在分段错误?它只是没有运行?是否显示错误? – pstrjds 2014-10-08 16:08:53

+0

是的,这是一个分段故障。 – gmeh94 2014-10-08 16:35:52

回答

1

您正在向函数传递struct queue *类型的指针q。但是你没有为该指针分配内存。

所以你需要分配内存到指针q,然后传递给你的函数。 你需要这样的

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

分配内存,然后通过q你的功能。

5

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

struct queue *q; 

请注意,您在这里不为结构分配内存。接下来,在你的main()函数调用:

createq(q); 

然后你在createq()功能通过q访问rearfront

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

这样你访问内存,你没有分配。你应该把像下面这样在你main()函数的开头:

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

而且不要忘了把free(q)main()函数的末尾,以防止内存泄漏。

+0

添加此代码后,代码正常工作。谢谢。 – gmeh94 2014-10-08 16:39:10

+0

不客气!我很高兴我的建议有效。 – honk 2014-10-08 16:40:19