java在最后一个节点之前添加第一个节点
我对java(Dobly链表)有一些问题。我必须在最后一个节点之前添加第一个节点。起初试图建造它,但没有成功。hier是我的dobly链接列表:
public class DoublyLinkedList<T>
{
private Element<T> first, last;
private int size;
public DoublyLinkedList()
{
first = last = null;
size = 0;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size == 0;
}
// --- hier is Problem!!! I have changed just hier. ---
public void apply( T o ) {
Element<T> e = new Element<T>(o);
Element<T> current = first;
Element<T> save = first;
for(int i = 0; i < size; i++){
current = current.getNext();
}
current.connectAsPrevious(e);
e.connectAsNext(save);
size++;
}
// --- bekannte Methoden ---
public void add( T content )
{
Element<T> e = new Element<T>( content );
if ( isEmpty() )
{
first = last = e;
}
else
{
last.connectAsNext( e );
last = e;
}
size++;
}
public void showAll()
{
Element<T> current = first;
while ( current != null )
{
if ( current.getContent() != null )
{
System.out.print( current.getContent().toString() );
if ( current != last )
{
System.out.print(", ");
}
}
current = current.getNext();
}
System.out.println();
}
// --- weitere Methoden zum Testen ---
public void build( T[] elems )
{
for ( T e : elems ) { add( e ); }
}
public String toString()
{
String result = "";
Element current = first;
while ( current != null )
{
result += current.getContent().toString();
if ( current != last )
{
result += ", ";
}
current = current.getNext();
}
return result;
}
// Element
private static class Element<E>
{
private E content;
private Element<E> previous, next;
public Element( E c )
{
content = c;
previous = next = null;
}
public E getContent()
{
return content;
}
public void setContent( E c )
{
content = c;
}
public boolean hasNext()
{
return next != null;
}
public Element<E> getNext()
{
return next;
}
public void disconnectNext()
{
if ( hasNext() )
{
next.previous = null;
next = null;
}
}
public void connectAsNext( Element<E> e)
{
disconnectNext();
next = e;
if ( e != null )
{
e.disconnectPrevious();
e.previous = this;
}
}
public boolean hasPrevious()
{
return previous != null;
}
public Element<E> getPrevious()
{
return previous;
}
public void disconnectPrevious()
{
if ( hasPrevious() )
{
previous.next = null;
previous = null;
}
}
public void connectAsPrevious( Element<E> e )
{
disconnectPrevious();
previous = e;
if ( e != null )
{
e.disconnectNext();
e.next = this;
}
}
}
}
我想我必须添加while
循环。因为如果大小0
为,则它将停止并出现错误NullPointerException
。对不起,我的英语不好
# 1 楼答案
得到NullPointerException的原因是,如果列表为空,则
current
为null(因为它被分配了first
的值,该值为null),并且current.connectAsPrevious
将引发异常如果不知道这种方法应该做什么,就很难提出替代方案。但是,可以通过将
if (current != null)
放在current.connectAsPrevious
之前来避免异常如果应该在列表中的最后一项之前添加该项(而不是作为最后一项),那么您应该只使用
last
引用,而不是从一开始就遍历列表: