我一直在尝试利用我之前制作的单链表创建一个双向链表。因此,在Node类中,我添加了上一个节点引用并更新了add
类中的insert
和List
方法,以适应DoublyLinked
列表类中的来回传递。 add
将新节点放在当前节点之后,insert
将新节点放在List
类的当前节点之前;这是因为我想在DoublyLinked
列表类中按升序添加和插入我的值。 [这可能听起来令人困惑,但我将在下面发布代码]当我在[{1}}类中测试我的add
方法时,我得到一个空指针异常。
正如我所说,我已经在这方面工作了几天,所以在那段时间我考虑了以前的这些问题:
List.java
DoublyLinked
DoublyLinked.java
public class List<T> implements ListInterface<T> {
protected class Node {
private T value = null;
private Node prev = null;
private Node next = null;
public T getValue( ) {
return value;
}
public Node getPrev( ) {
return prev;
}
public Node getNext( ) {
return next;
}
public void setValue( T newValue ) {
value = newValue;
}
public void setPrev( Node prevNode ) {
prev = prevNode;
}
public void setNext( Node nextNode ) {
next = nextNode;
}
}
protected Node head = null;
protected Node cur = null;
protected int size = 0;
// add after cur
@Override
public void add( T value ) {
Node temp = new Node( );
temp.setValue( value );
size++ ;
if (isEmpty( )) {
head = temp;
cur = temp;
} else {
temp.setNext(cur.getNext());
temp.setPrev(cur);
cur.setNext(temp);
cur = temp;
}
}
// insert before cur
@Override
public void insert( T value ) {
Node temp = new Node( );
temp.setValue( value );
size++ ;
if (isEmpty( )) {
head = temp;
cur = temp;
} else if (head == cur) {
head = temp;
head.setNext( cur );
cur.setPrev(head);
cur = head;
} else {
Node prev = head;
while( prev.getNext( ) != cur ) {
prev = prev.getNext( );
}
temp.setNext( prev.getNext( ) );
temp.setPrev(prev);
prev.setNext( temp );
cur = temp;
}
}
}
然后我有一个基本的JUnit测试来测试代码:
public class DoublyLinked<T extends Comparable<T>>
extends List<T> implements ListInterface<T> {
private int size;
private Node tail;
DoublyLinked() {
this.size = 0;
this.tail = null;
}
@Override
public void add(T value) {
size++;
reset();
// getting Null pointer on add when doublinked list is empty
if(isEmpty()) {
super.add(value);
head = cur;
tail = head;
cur = head;
}
else {
try {
while(value.compareTo(get()) > 0 && hasNext()) { // error here
next();
if(value.compareTo(get()) <= 0) {
super.add(value);
// how to set cur to this new node?
}
}
} catch (EmptyListException | EndOfListException e) {}
super.add(value); // add at end of list
tail = cur;
cur = tail;
}
}
@Override
public T get() throws EmptyListException {
return cur.getValue();
}
@Override
public T next() throws EmptyListException, EndOfListException {
if (!hasNext( )) {
throw new EndOfListException( );
}
cur = cur.getNext( );
return cur.getValue( );
}
@Override
public boolean hasNext() {
return((!isEmpty()) && (cur.getNext() != null));
}
@Override
public void reset() {
cur = head;
}
@Override
public boolean isEmpty() {
return size == 0;
}
}
答案 0 :(得分:0)
您递增size
然后调用isEmpty()
(检查size
是否为零)来决定如何添加项目:
size++ ;
if (isEmpty( )) {