【问题标题】:difficulties implementing queue by linked- list in java在java中通过链表实现队列的困难
【发布时间】:2017-10-02 20:01:08
【问题描述】:

最近我在java中阅读了一个enqueue的实现,并且对其中几行的含义感到非常困惑。

public void enqueue(String item) {
    Node oldlast = last;
    last = new Node();
    last.item = item;
    last.next = null;

    if (isEmpty())
        first = last;
    else
        oldlast.next = last;
}

我很困惑,既然 oldlast 仅在这种方法中创建,为什么我们要在 else 之后声明“oldlast.next=last”?用完方法会被销毁吧?

另外,如果我们只在 first 为空时添加 last 到 first ,如果我添加两个节点然后删除两个节点会不会有问题?由于第一个节点只添加了一个,我想删除两个会不会有异常?

【问题讨论】:

    标签: java linked-list queue


    【解决方案1】:
    public void enqueue(String item)
    {
        Node oldlast = last; // last points to some Node_A, oldlast also will point at the same object
        last = new Node(); // Now last points to new object (Node_B), old last still points to Node_A
        last.item = item;
        last.next = null;
        if (isEmpty()) first = last;
        else oldlast.next = last;
    }
    

    【讨论】:

      【解决方案2】:

      oldLast 不是创建的,它只是对与last 相同的对象的引用。

      public void enqueue(String item)
      {
          Node oldlast = last; // oldLast -> nodeX, last -> nodeX
          last = new Node(); // oldLast -> nodeX, last -> nodeY
          last.item = item;
          last.next = null;
          if (isEmpty()) first = last;
          else oldlast.next = last; // change the nodeX
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-15
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        • 2011-06-28
        • 1970-01-01
        • 1970-01-01
        • 2021-03-21
        相关资源
        最近更新 更多