我正在尝试将使用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的索引,我不知道如何在该索引处引用特定的shape类型。另外,我需要有关remove方法的帮助。我觉得一旦我得到了第一个吸气剂的必要信息,我遇到了麻烦,我应该能够解决我的第二个问题。有没有人有有用的建议?
答案 0 :(得分:0)
public Shape get(int index) {
ShapeNode temp = head;
while(index-- > 0) {
temp = temp.next;
}
if(temp == null)
throw new IndexOutOfBoundsException("Invalid index : " + index);
Shape rem = temp.shp;
return rem;
}
但这是O(n)
是LinkedList。