c - 使用 C 中的链表和结构实现队列

标签 c linked-list queue structure

我不明白这段代码有什么问题。编译期间没有错误,但在执行 Enqueu 的给定选项时,它突然停止。问题发生在 Queue->rear->next=NULL 附近,在我看来这是正确的。我不知道我哪里错了。

struct ListNode
{
       int data;
       struct ListNode *next;
};

struct Queue
{
      struct ListNode *front;
      struct ListNode *rear;
};

struct Queue *createQueue()
{
      struct Queue *Q;
      Q=malloc(sizeof(struct Queue));
      if(!Q)
           return NULL;
      Q->front=Q->rear=NULL;
      return Q;
}

int IsEmptyQueue(struct Queue *Q)
{
      return (Q->front==NULL);
}

int EnQueue(struct Queue *Q,int data)
{
    struct ListNode *newNode;
    newNode=malloc(sizeof(struct ListNode));
    if(!newNode)
               return NULL;
    newNode->data=data;
    newNode->next=NULL;
    Q->rear->next=newNode;
    Q->rear=newNode;
    if(Q->front==NULL)
                Q->front=newNode;
}

int main()
{
    int choice=0,size,n;
    struct Queue *q;
    while(1)
    {
         printf("\nEnter the following");
         printf("\n1. Create a queue "); 
         printf("\n2.Enqueue");
         printf("\n7.Exit ");
         scanf("%d",&choice);

         switch(choice)
         {
                    case 1:printf("\nCreate Queue");
                           q=createQueue();
                           break;
                    case 2:printf("\nInsert");
                           printf("\nEnter element to be inserted");
                           scanf("%d",&n);
                           EnQueue(q,n);
                           break;

                    case 7:exit(0);
                    break;

      }
   }
}

最佳答案

当队列为空时,其frontrear成员为NULLEnQueue 然后取消引用该行中的 NULL 指针

Q->rear->next = newNode;

第一次调用时。此行不是必需的,因此可以简单地删除。

还有一些其他小错误您还可以查看

  • createQueue 泄漏 temp。您显然不需要声明/分配这个
  • EnQueue 缺少对 malloc newNode 失败的错误处理。打印出“newNode Created”在这里有些误导!
  • 在打印指向队列尾部的指针时,使用 %p 作为格式说明符。

关于c - 使用 C 中的链表和结构实现队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14260976/

相关文章:

javascript - 如何在 javascript 中对传入的 websocket 事件进行排队以执行缓慢?

c - 在 avformat_alloc_output_context2 中使用什么 format_name?

java - 如何在 Java 中打印变量的地址

hadoop - 在特定队列上运行 sqoop 作业

Azure 函数 : Could not load file or assembly WebJobs. 主机

c - 链表删除并返回第一个元素

c - 如何找到无符号长整型中的所有质因数?

C - 成员引用基类型 'int' 不是结构或 union

c - 如何从独立环境中关闭计算机?

java - 自定义链接列表中的 JTable 数据存在问题