尝试在链表java类的指定索引处插入对象。我不太确定如何实现这个。
下面是一个方法参数的例子,以及我到目前为止所拥有的(不工作):
void insertAtIndex(int idx, Shape data){
if (idx == 0) {
//insert the new Shape at the beginning of the list
insertAtBeginning(data);
}else{
Node temp = head;
for(int i = 0; i < idx - 1; i++)
temp = temp.getNext();
Node next = new Node(data);
next = temp.getNext();
temp = next;
}
}
Node的子类:
public Node(Shape data){
//Make next point to null
next = null;
this.data = data;
}
// another Node constructor if we want to specify the node to point to.
public Node(Shape dataVal, Node nextVal){
next = nextVal;
data = dataVal;
}
//Getter for data
public Shape getData(){
return data;
}
//Setter for data
public void setData(Shape data){
this.data = data;
}
//Getter for next
public Node getNext() {
return next;
}
//Setter for next
public void setNext(Node next) {
this.next = next;
}
链表类:
public class ShapeLinkedList {
public Node head; //head is first node in linked list
public Node tail; //tail is last node in linked list
public ShapeLinkedList(){}
public ShapeLinkedList(Node head){
head = null;
tail = null;
}
public boolean isEmpty(){
return length() == 0;
}
就用LinkedList#add(int index, E element)
:
public void add(int index, E element)
将指定元素插入此列表中的指定位置。移动当前在该位置的元素(如果有的话)和右边的任何后续元素(在它们的指数)。
开头不错:D
现在你需要这样看……
a -> b -> c -> d
如果你想在索引0处添加…
e -> a ->…对吧?
如果你的索引是1,那么…
a-> e -> b -> c -> d也就是说,索引项AT指向新形状,新形状指向原来在索引2中的下一个项(但AFTER将是索引3)