【问题标题】:Circular list add and remove methods循环列表添加和删除方法
【发布时间】:2014-10-16 17:05:36
【问题描述】:

如何让我的添加和删除方法从普通链接到循环链接列表。使用这段代码,我想我需要一个尾引用等等?

 public void add(int index, Object item)
                  throws ListIndexOutOfBoundsException {


     //our index needs to go in along with our stuff in item
        Node temp = new Node(item);
        Node current = head;

        for(int i = 1; i < index && current.getNext() != null; i++)
        {
            current = current.getNext();
        }
        // set the new node's next-node reference to this node's next-node reference
        temp.setNext(current.getNext());
        // now set this node's next-node reference to the new node
        current.setNext(temp);
    //  current.setPrevious();
        numItems++;// increment the number of elements variable

  }  

  public boolean remove(int index) 
                   throws ListIndexOutOfBoundsException {

      if(index < 1 || index > size())
            return false;

        Node current = head;
        for(int i = 1; i < index; i++)
        {
            if(current.getNext() == null)
                return false;

            current = current.getNext();
        }
        current.setNext(current.getNext().getNext());
        numItems--; // decrement the number of elements variable
        return true;


  }   // end remove

【问题讨论】:

    标签: java linked-list circular-list


    【解决方案1】:

    在循环链表中,current.getNext() 不会是null。您必须以另一种方式检查何时到达列表末尾(current.getNext() == null 将始终为 false)。

    第一个选项是与头节点比较,即如果current.getNext() == head,那么current是列表中的最后一个元素,你可以停止。

    但是由于无论如何您都在计算索引,因此您也可以确保索引始终介于 0 和 size() 之间(无论如何,您目前在您的 remove 方法中都这样做)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      相关资源
      最近更新 更多