How does this enqueue function work?

Question:

I'm having trouble understanding this line:

rear->next = temp;

in this queue function:

 void Queue::enqueue(int data) {

    Node *temp = new Node();    // make a temporary node
    temp->info = data;          // assign passed in data to it
    temp->next = 0;             // make it point to null

    if(front == 0)              // if there is no front node
        front = temp;           // make this a front node

    else                        // else, if there is already a front node
        rear->next = temp;      // make this rear's next pointer???? why?

    rear = temp;                // in any case make this a rear node

}

Wouldn't it make more sense to do it like this?

    else                    // else, if there is already a front node
        temp->next = rear;  // make temp point to REAR; not other way around

    rear = temp;                // make temp a new rear node

Answer:

  
  

The rear points to the last element. What is wanted is to place temp after the current rear, and then move rear to point to the newly placed last element. So, if we were wanting to enqueue 4 to the queue (1, 2, 3), we want:

1 -> 2 -> 3 -> 4
|              |
front          rear

Your solution lets temp cut in front of the current rear, and then moves rear to the cut position. It doesn't even cut properly, since the item before the rear is still pointing to the original rear. The rear isn't pointed to the last item anymore, and your queue would thus be in an inconsistent state.

1 -> 2 -> 3
|      4 -^
|      |
front  rear

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值