Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 循环列表添加和删除方法_Java_Linked List_Circular List - Fatal编程技术网

Java 循环列表添加和删除方法

Java 循环列表添加和删除方法,java,linked-list,circular-list,Java,Linked List,Circular List,如何将我的添加和删除方法从普通链接列表添加到循环链接列表。使用这段代码,我想我需要一个尾部引用等等 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);

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

 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
public void add(整数索引,对象项)
抛出ListIndexOutOfBoundsException{
//我们的索引需要与项目中的内容一起输入
节点温度=新节点(项目);
节点电流=头;
对于(int i=1;i大小())
返回false;
节点电流=头;
对于(int i=1;i
在循环链表中,
current.getNext()
将不会为
null
。当您以另一种方式到达列表末尾时,必须进行检查(
current.getNext()==null
将始终为
false

第一个选项是与head节点进行比较,即如果
current.getNext()==head
,则
current
是列表中的最后一个元素,您可以停止

但是,由于您仍在计算索引,因此也可以确保索引始终在0和
size()
之间(您目前在remove方法中仍然这样做)