[英]Implementing special linked-list method in Java
Is it possible to create a linked list in Java, with the ability to add new links anywhere in the middle (not just at the beginning or end) of the list -- if possible, without copy-pasting in memory large parts of the list to accommodate for entry of a new link? 是否可以在Java中创建链接列表,能够在列表的中间(不仅仅是开头或结尾)的任何位置添加新链接 - 如果可能的话,不在内存中复制粘贴大部分列表容纳新链接的输入?
If so, please post your example!! 如果是这样,请发贴你的例子!!
You can use LinkedList to do this. 您可以使用LinkedList执行此操作。
List<Integer> ints = new LinkedList<Integer>();
for (int i = 0; i <= 10; i++)
ints.add(i / 2, i);
System.out.println(ints);
prints 版画
[1, 3, 5, 7, 9, 10, 8, 6, 4, 2, 0]
As you can see it has been adding entries in the middle of the list. 如您所见,它一直在列表中间添加条目。
Java中的LinkedList
类已经通过其add(index, element)
方法实现了这一点。
In pseudo code something link this is a good place to start: 在伪代码链接中,这是一个很好的起点:
public LinkedList<E> implements List<E>{
...
public void add(int index, E element){
Node<E> current=findNodeAt(index);
//add in your logic to insert this node at this location
//probably something like (depending on your linking)
element.setNext({current nodes next value})
current.setnext(element);
}
private Node<E> findNodeAt(index){
//iterate through list until you reach the index or end of the list
//then return that node
}
...
}
public Node<E>{
private Node<E> next;
...
Node<E> setNext(Node<E> next){
Node<E> previousNext=next;
this.next=next;
return previousNext;
}
...
}
LinkedList
实现'List'接口,它有你需要的add方法: http : //docs.oracle.com/javase/7/docs/api/java/util/List.html#add%28int,%20E%29
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.