java如何创建我自己的单链表
我正在尝试将使用ArrayList的代码转换为适用于单链接列表的代码。数组列表由之前创建的形状对象组成,我知道它们是有用的。然后,可以将新形状添加到数组列表的末尾。此外,可以使用索引引用从此列表中删除特定形状。然而,当我把它切换到一个链表时,我并没有得到我需要的东西。以下是数组列表的代码:
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;
}
}
}
我需要帮助构建形状的getter,因为我不知道如何找到LinkedList的索引,也不知道如何在该索引处引用特定的形状类型。另外,我需要有关删除方法的帮助。我觉得,一旦我获得了第一个遇到问题的getter所需的信息,我就应该能够解决第二个问题。有人有什么有用的建议吗
# 1 楼答案
但这是
O(n)
链接列表