【问题标题】:Unable to understand the logic in enqueue function无法理解入队函数中的逻辑
【发布时间】:2015-04-06 10:03:51
【问题描述】:

我通过代码在队列中插入元素,但我无法理解 show 函数的工作原理

void enqueue(int x)
{
  queue *ptr;
  queue *ptr1;
  ptr=(queue*)malloc(sizeof(queue));
  ptr->info=x;
  if(front==rear&&front==NULL)
  {
      ptr->next=NULL;
      front=rear=ptr;
  }
  else
    {
   while(rear->next!=NULL)
   {
       rear=rear->next;
   }
   rear->next=ptr;
   ptr->next=NULL;
  }
}

//由于前后之间没有链接,我无法理解 next to front 是如何指向队列中的下一个元素的

 void show()
 {
  queue *ptr=front;
  while(ptr!=NULL)
   {
    printf("%d\n",ptr->info);
    ptr=ptr->next;
   }
}

【问题讨论】:

    标签: c data-structures queue


    【解决方案1】:

    前后没有联系

    当然有 - 这是它的建立方式:

    if(front==rear&&front==NULL)
    {
        ptr->next=NULL;
        front=rear=ptr;
    }
    

    front 指向第一个插入的元素。最初,rear 也指向同一个元素。当您向队列中添加更多元素时,rear 继续前进,而front 仍然指向相同的初始元素。

    show() 获取该元素,并使用它遍历链表。

    请注意,如果始终使用insert 插入项目,则不需要while 循环,因为rear->next!=NULL 始终为“假”。

    【讨论】:

    • 但是我已经指定了 front->next 将指向后方
    • @Newbie786 在第二次调用insert() 的开头,frontrear 指向同一个元素。当你在rear->next处插入一个元素时,front->next也指向同一个元素,因为front==rear
    • 好的,我明白了
    【解决方案2】:

    这是你的代码,我正在让 cmets 你的代码在做什么。

    void enqueue(int x)
    {
      queue *ptr;
      queue *ptr1;
      ptr=(queue*)malloc(sizeof(queue));  // allocating memory
      ptr->info=x;  // x is the value you are passing to ptr.
      if(front==rear&&front==NULL) //this work for the first time when list is empty
      {
          ptr->next=NULL;    //setting next location to null
          front=rear=ptr;    //till now only once value is there in the list so front=rear (both will be same) = ptr
      }
      else
      {
           while(rear->next!=NULL)  // while loop will run until end of the list reached
           {
               rear=rear->next;     // moving to next location
           }
    
       rear->next=ptr;     // after getting last location assign it to rear->next
       ptr->next=NULL;   // again make next loation null.
      }
    }
    

    【讨论】:

    • 但是显示功能是如何工作的,因为前后没有链接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2017-07-18
    相关资源
    最近更新 更多