C中的队列在弹出所有元素后行为异常

C中的队列在弹出所有元素后行为异常,c,queue,C,Queue,我这样定义我的队列: struct Node { int Data; struct Node* next; }*rear, *front; int pop() { struct Node *temp, *var=rear; int data = var->Data; if(var==rear) { rear = rear->next; free(var); }

我这样定义我的队列:

struct Node
 {
  int Data;
  struct Node* next;
 }*rear, *front;

int pop()
{
      struct Node *temp, *var=rear;
      int data = var->Data;
      if(var==rear)
      {
             rear = rear->next;
             free(var);
      }
      else{
      printf("\nQueue Empty");
      }
      return data;
}

void push(int value)
{
     struct Node *temp;
     temp=(struct Node *)malloc(sizeof(struct Node));
     temp->Data=value;
     if (front == NULL)
     {
           front=temp;
           front->next=NULL;
           rear=front;
     }
     else
     {
           front->next=temp;
           front=temp;
           front->next=NULL;
     }
}
当我弹出队列中的最后一个元素时,我无法推送更多的元素

结果:

1. Push to Queue
2. Pop from Queue
3. Display Data of Queue
4. Exit

5. Empty Choose Option: 1

Enter a valueber to push into Queue: 10
Calling push with 10, temp at 8061420. push done: front = 8061420, rear = 8061420
Elements are as:        10

Choose Option: 1

Enter a valueber to push into Queue: 20
Calling push with 20, temp at 8061430. push done: front = 8061420, rear = 8061430
Elements are as:        20

Choose Option: 2
Elements are as:        20

Choose Option:

从开头开始,如果未将
front
reast
某处设置为NULL,则所有这些都不起作用

然后让我们看一下
push()

当列表为空时,您将
front
reast
设置为等于
temp
。那很好。当有
front
时,您可以设置
front->next=temp如果您已经在列表中添加了其他内容,则这不好。建议使用
rear
始终指向添加到列表中的最后一项,并始终添加到
rear
的末尾

所以你应该:

void push(int value)
{
  struct Node * temp= (struct Node *) malloc( sizeof( struct Node)) ;
  temp-> Data= value ;
  temp-> next= NULL ;
  fprintf(stderr, "Calling push with %d, temp at %lx.\n", value, temp) ;

  if ( rear) { rear-> next= temp ;  rear= temp ; }
    else { front= rear= temp ; }

  fprintf(stderr, "push done: front = %lx, rear = %lx\n", (long) front, (long) rear) ;
}
类似地,在
pop()
上也有一些倒退。您可以查看
rear
,还可以检查
rear->next
<代码>后->下一步
始终
。取而代之的是,只需去掉前面的第一件事。但比这更糟糕的是,在检查
rear
是否为空之前,您会查看它的值。这会做坏事。因此,首先测试指针是否有效,然后读取其值:

int pop()
{
  int retval= -1 ;
  if ( front )
  {
    struct Node * temp= front ;
    front= front-> next ;
    if ( ! front ) { rear= front ; }
    retval= temp-> Data ;
    free( temp) ;
  }
  return retval ;
}
这会让你动手术的。
}

您对队列的概念是错误的。队列中的插入是从后面完成的,弹出是从前面完成的。你正在做的是堆栈。变量可能会让它看起来像这样,但执行时不是这样。无论如何,这并没有开始回答我的问题。在第二次按下
后,它显示
是一个值,而
是另一个值。因此,列表中有两个值。当你启动
display()
函数时,你需要看看
front
reast
是什么。这会在你每次按下时替换第一个/最后一个。@PandaBearSoup为什么你认为
first
会在每次按下时被替换?我刚刚测试过,列表中没有添加任何内容。我真的很感谢你迄今为止的帮助,并理解你的意思。使用此选项显示列表:void display(){struct Node*var=front;if(var!=NULL){printf(“\n元素为:”);while(var!=NULL){printf(“\t%d”,var->Data);var=var->next;}printf(“\n”);}else printf(“\nQueue为空”);}因此,第一次调用
push()
时,它应该创建一个
节点
,然后将其分配给
前部
后部
。您的意思是不会发生这种情况吗?请确保在某个地方将
front
reast
初始化为NULL。