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方法中仍然这样做)