如何在Java链接列表中的指定索引处插入Object

时间:2016-10-13 04:02:07

标签: java linked-list

尝试在链表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;
}

2 个答案:

答案 0 :(得分:2)

只需使用LinkedList#add(int index, E element)

  

public void add(int index, E element)

     

将指定元素插入此列表中的指定位置。移动当前位于该位置的元素   (如果有的话)和右边的任何后续元素(在他们的   指数)。

答案 1 :(得分:0)

好的开始:D

现在你需要像这样看待它......

a - &gt; b - &gt; c - &gt; d

如果您想在索引0处添加...

e - &gt; a - &gt; ......对吗?

如果您将其索引为1,那么......

A-&GT; e - &gt; b - &gt; c - &gt; d

换句话说,索引指向新形状的项目AT,新形状指向曾经位于索引2中的下一个项目(但它将是索引3之后)

相关问题