我正在尝试将适用于 ArrayLists 的代码转换为适用于单链表的代码。数组列表由之前创建的 Shape 对象组成,我知道工作。然后,可以将新形状添加到数组列表的末尾。此外,可以使用索引引用从此列表中删除特定形状。但是,当我将其切换到链接列表时,我并没有得到我需要的东西。这是数组列表的代码:
import java.util.ArrayList;
public class ShapeLinkedList {
ArrayList<Shape> list = new ArrayList<Shape>();
public ShapeLinkedList() {
}
public void addToRear(Shape shape) {
list.add(shape);
System.out.println("Added "+shape);
}
public Shape get(int index) {
return list.get(index);
}
public int size() {
return list.size();
}
public Shape remove(int index) {
Shape temp = list.remove(index);
System.out.println("Removed "+temp);
return temp;
}
}
我不能更改方法的名称,我必须使用所有相同的方法。所以这就是我到目前为止的链表:
public class ShapeLinkedList {
ShapeNode head;
int count = 0;
public ShapeLinkedList() {}
public void addToRear(Shape shape) {
ShapeNode end = new ShapeNode(shape);
if (head == null) {
head = end;
}
//loop through Linked List until we find the end of the list
while (head.next != null) {
head = head.next;
count++;
}
//set the new node to the Shape shape and the next one will be null
head.next = end;
count++;
//System.out.println("Added " + shape);
}
public Shape get(int index) {
for (int i = 0; i <= index; i++) {
}
Shape rem = ;
return rem
}
public int size() {
return count;
}
public Shape remove(int index) {
if (index == 0) {
Shape temp = head;
head = head.next;
} else if () {
Shape temp = ;
}
//System.out.println("Removed " + temp);
return temp;
}
private class ShapeNode {
Shape shp;
ShapeNode next;
public ShapeNode(Shape shp) {
this.shp = shp;
next = null;
}
}
}
我需要帮助构建 Shape 的 getter,因为我不知道如何找到 LinkedList 的索引,也不知道如何在该索引处引用特定的形状类型。另外,我需要删除方法的帮助。我觉得一旦我获得了第一个遇到问题的吸气剂的必要信息,我应该能够解决我的第二个问题。有人有有用的建议吗?