我想用链表实现显示队列的当前状态,printqueue
尝试这样做。
我上面说的 printqueue
试图做到这一点,但我不能编辑它的内部代码或任何函数或结构。所以我唯一可以拥有的解决方案是改变我调用它的方式(使用不同的参数初始化)。当我在空队列中运行这段代码时,我遇到了段错误,或者在非空队列中我什么也没做。
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PLATE_LENGTH 9
struct node
{
char data[PLATE_LENGTH];
struct node *next;
};
typedef struct node *PTR;
void enqueue(char obj[],PTR *pf,PTR *pr)
{
PTR newnode;
newnode=(PTR*)malloc(sizeof(PTR));
assert(newnode!=NULL);
strcpy(newnode->data,obj);
newnode->next=NULL;
if((*pf)==NULL)
{
*pf=newnode;
*pr=newnode;
}
else
{
(*pr)->next=newnode;
*pr=newnode;
}
printf("Insertion Completed!\n");
}
void dequeue(PTR *pf,PTR *pr)
{
PTR p;
if((*pf)==NULL)
printf("\nQueue empty. No elements to delete.\n");
else
{
p=*pf;
*pf=(*pf)->next;
if((*pf)==NULL) *pr=*pf;
printf("%s has been deleted...\n",p->data);
free(p);
}
}
void printqueue(PTR p,PTR pr)
{
while(p!=NULL)
{
printf("\n\t\t%s",p->data);
p=p->next;
}
}
int edisplay_menu()
{
int input=0;
printf("MENU\n======\n1.Car Arrival\n2.Car Departure\n3.Queue State\n0.Exit\n");
printf("Choice?");
scanf("%d",&input);
return input;
}
PTR *pf=NULL,*pr=NULL;
int main(int argc, char** argv)
{
int input=1;
char *plate=(char*) malloc(PLATE_LENGTH*sizeof(char));
PTR front,rear;
if (plate==NULL)
{
printf("Out of memory!\n");
return (1);
}
input=edisplay_menu();
while(input!=0)
{
if(input==1) //in case of car arrival
{
printf("Give the car's plate:");
scanf("%s",plate);
enqueue(plate,&pf,&pr); //insert car plate to queue
}
if(input==2) //in case of departure
{
dequeue(&pf,&pr); //delete car plate from queue
}
if(input==3)
{
front=*pf;
printqueue(front,rear); //display all car plates in queue
}
if(input==0)
{
printf("Bye!!!");
exit(1);
}
input=edisplay_menu();
}
return (EXIT_SUCCESS);
}
最佳答案
看来您对要使用的变量感到困惑。
你有全局变量:
PTR *pf=NULL,*pr=NULL;
在main
里面你有:
PTR front,rear;
然后使用 pf
和 pr
进行入队,使用 front
和 rear
进行打印。
解决方案:摆脱全局变量(注意目前它们也有错误的类型)
顺便说一句:front
和 rear
在调用 print 函数时未初始化,这可能会导致崩溃。
关于c - 如何使用链表在 C 中显示队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56225109/