gpt4 book ai didi

java - 如何在Java链表中的指定索引处插入对象

转载 作者:行者123 更新时间:2023-12-02 03:18:12 25 4
gpt4 key购买 nike

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

}
}

节点的子类:

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)

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

关于java - 如何在Java链表中的指定索引处插入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40012081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com