以下是我使用链表实现队列。我对数据结构完全陌生,正在尝试实现队列数据结构。这段代码编译成功,但一旦我尝试运行它,程序就会崩溃。我不知道怎么做解决这个问题。如果你们有任何线索,我的代码有什么问题,请给我一个想法。
谢谢你的帮助。
这是我的 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;
}