【发布时间】:2021-10-19 17:23:22
【问题描述】:
我正在为我的数据结构类开发一个项目,该项目要求我编写一个类来实现整数的链表。
- 为节点使用内部类。
- 包括以下方法。
- 编写一个测试器,使您能够以任何顺序使用您想要的任何数据来测试所有方法。
我有一个名为“public void insertAt(int index, int item)”的方法。此方法旨在“在位置索引处插入一个项目,其中索引传递给该方法”我在下面有此方法的代码。当我在索引处插入一个项目时,它可以工作,除非它是列表中的最后一个项目。当我尝试在列表末尾插入一个项目时,它会替换最后一个项目,并且之前存在的项目在不应该时被删除。例如,如果我有一个列表:“[9, 8, 15, 7, 5, 15, 19, 6, 19, 2]”并且我想插入数字“90”和最后一个索引它应该看起来像[9, 8, 15, 7, 5, 15, 19, 6, 19, 90, 2] 但我得到 [9, 8, 15, 7, 5, 15, 19, 6, 19, 90]。如何在我的代码中解决这个问题,以便如果我在尾部插入一个项目,它会将我想要插入的项目移动到尾部之前?
import java.util.Random;
import java.util.Scanner;
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(LinkedListOfInts other) {
Node tail = null;
for (Node n = other.head; n != null; n = n.nextNode) {
if (tail == null)
this.head = tail = new Node(n.value, null);
else {
tail.nextNode = new Node(n.value, null);
tail = tail.nextNode;
}
}
}
public LinkedListOfInts(int[] other) {
Node[] nodes = new Node[other.length];
for (int index = 0; index < other.length; index++) {
nodes[index] = new Node(other[index], null);
if (index > 0) {
nodes[index - 1].nextNode = nodes[index];
}
}
head = nodes[0];
}
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);
prev.nextNode = newItem;
if (temp.nextNode != null) {
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) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
boolean done = false;
while (!done) {
System.out.println("1. Insert At");
System.out.println("2. toString");
switch (input.nextInt()) {
case 1:
System.out.println("Insert an Item to a certain Index on the List");
list.insertAt(input.nextInt(), input.nextInt());
break;
case 2:
System.out.println("toString");
System.out.println(list.toString());
break;
}
}
}
}
【问题讨论】:
标签: java linked-list nodes tail