【发布时间】:2021-10-21 02:08:57
【问题描述】:
我有一个名为“public void insertAt(int index, int item)”的方法。此方法旨在“在位置索引处插入一个项目,将索引传递给该方法”我在下面有此方法的代码。当我在索引处插入一个项目时,它会起作用,除非它是列表中的第一个项目。当我尝试在列表的开头插入一个项目时,没有任何反应。例如,如果我有一个列表:“[9, 8, 15, 7, 5, 15, 19, 6, 19, 2]”并且我想在第一个节点中插入数字“90”,它应该看起来像[90, 9, 8, 15, 7, 5, 15, 19, 6, 19, 2] 但我得到的是“[9, 8, 15, 7, 5, 15, 19, 6, 19, 2]” .如何在我的代码中解决此问题,以便如果我要在头部插入一个项目,它会将我想要插入的项目移动到头部,并将所有其他项目移到列表中?
import java.util.Random;
public class LinkedListOfInts {
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++)
this.addToFront(random.nextInt(high - low) + low);
}
public void addToFront(int x) {
head = new Node(x, head);
}
public void insertAt(int index, int item) {
Node temp = head;
Node prev = null;
int i = 0;
for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
if (index == i) {
Node newItem = new Node(item, null);
if (prev != null) {
prev.nextNode = newItem;
}
newItem.nextNode = temp;
}
if (temp.nextNode != null) {
prev = temp;
temp = temp.nextNode;
i++;
}
}
}
public String toString() {
String result = "";
for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
if (!result.isEmpty()) {
result += ", ";
}
result += ptr.value;
}
return "[" + result + "]";
}
public static void main(String[] args) {
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
System.out.println(list.toString());
list.insertAt(0, 27);
System.out.println(list.toString());
}
}
【问题讨论】:
-
这是与stackoverflow.com/questions/69653506/… 不同的问题吗?我对这个问题留下了有用的评论。
标签: java linked-list nodes