public class A<E> extend AbstractList<E>{
private SLNode<E> Head = new SLNode<E>
private int length = 0; // length of the list
// I will skip the class of SLNode<E>
// Head's element and successor is initialized as null in the class SLNode<E>
public void add(int index, E element) // insert an element in the list
{
// if index is less than 0 or greater than the length
if((index < 0) || (index > length))
throw new IndexOutOfBoundsException();
if(index ==0)
{
SLNode<E> newnode = new SLNode<E>(element, null); // make new node
newnode.setSuccessor(Head.getSuccessor());
Head.setSuccessor(newnode);
length++;
}
}
Q1。这是在列表前面加入元素的正确方法吗? (使用虚拟头节点,但没有尾) Q2。列表是空的还是非空的,它是一样的吗?Java:单链表,虚节点,插入
这是你的一般方法插入或头部方法中插入? – smk
是啊..我应该在使用虚拟头节点,但无尾指针.. – hibc
小提示,无关的答案前面添加的元素:不要用大写字母开头的变量。类以一个大写开头 - Head.getSuccessor()看起来像是在Head类中访问一个静态方法。 – Jiman