我想写Deque的实现 我在下面编写了代码,但不幸的是我遇到了问题 当我使用addFirst和addLast甚至removeFirst时,每件事都可以 但是当我使用removelast时,程序会抛出NullPointerException 我不知道究竟是什么问题所以我真的很困惑 任何人都可以帮我吗? 提前感谢您的关注
Node Class ::
public class Node<E>{
E element;
Node<E> prev , next;
public Node(E element, Node<E> prev, Node<E> next) {
this.element = element;
this.prev = prev;
this.next = next;
}
public Node() {
this(null, null, null);
}
public void setNext(Node next)
{
this.next = next;
}
public void setPrev(Node prev)
{
this.prev = prev;
}
public Node getNext()
{
return next;
}
public Node getPrev()
{
return prev;
}
}
这里是Deque Interface ::
public interface DQ<E> {
public int size();
public boolean isEmpty();
public E getFirst();
public E getLast();
public void addFirst (E element);
public void addLast (E element);
public E removeFirst();
public E removeLast();
}
最后是MyDQ Class,它实现了DQ class ::
public class MyDQ<E> implements DQ<E>{
Node<E> head , tail;
int size = 0;
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public E getFirst() {
if(head == null)
return null;
return head.element;
}
@Override
public E getLast() {
if(head == null)
return null;
return tail.element;
}
@Override
public void addFirst(E element) {
Node<E> n = new Node<>(element, null, null);
if(head == null)
head = tail = n;
else
{
head.setPrev(n);
n.setNext(head);
head = n;
}
size++;
}
@Override
public void addLast(E element) {
Node<E> n = new Node<>(element, null, null);
if(head == null)
head = tail = n;
else
{
tail.setNext(n);
n.setPrev(head);
tail = n;
}
size++;
}
@Override
public E removeFirst() {
if(head == null)
return null;
Node<E> n = head;
head = head.getNext();
head.setPrev(null);
n.setNext(null);
size --;
return n.element;
}
@Override
public E removeLast() {
if(head == null)
return null;
Node<E> n = tail;
tail = tail.getPrev();
tail.setNext(null);
n.setPrev(null);
size --;
return n.element;
}
}
答案 0 :(得分:2)
我创建了一个简单的Person对象:
public class Person {
String name;
Integer age;
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
}
我使用以下单元测试对此进行了测试:
@Test
public void testOneElementDeque() {
MyDQ<Person> deq = new MyDQ<>();
Person p1 = new Person("John", 12);
Person p2 = new Person("Eric", 45);
deq.addLast(p1);
assertEquals(p1, deq.getLast());
assertEquals(p1, deq.getFirst());
deq.removeLast();
}
这会在此行抛出一个空指针(第78行):
tail.setNext(null);
此时调用尾部已被此行设置为null:
tail = tail.getPrev();
为了纠正这个问题,我在这一点上将实现重写为null check tail:
public E removeLast() {
if(tail == null)
return null;
Node<E> n = tail;
tail = tail.getPrev();
if(tail != null)
tail.setNext(null);
n.setPrev(null);
size --;
return n.element;
}