zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [Clojure] 包管理器leiningen配置国内镜像仓库
    [Haskell] 为什么列表操作++很昂贵?
    js判断除了空格换行之外是否为空
    iOS上架之隐私信息访问权限(uni-app)
    vue之动态绑定class
    this
    uni-app 上传图片之压缩图片上传
    uniapp无痛刷新token
    jQuery 发送跨域请求(jsonp)
    Document
  • 原文地址:https://www.cnblogs.com/vigorz/p/10499160.html
Copyright © 2011-2022 走看看