0
教科書「Java 6Eでのデータ構造とアルゴリズム」にあります。この実装は、新しいノードを作成しようとすると、addFirstメソッドとaddLastメソッドでエラーが発生します。これは、コードSingly Linked Listのこの教科書実装で何が問題になりますか?
public class SinglyLinkedList<E> {
private static class Node<E>{
private E element;
private Node<E> next;
public Node(E e, Node<E> n){
element = e;
next = n;
}
public E getElement(){
return element;
}
public Node<E> getNext(){
return next;
}
public void setNext(Node<E> n){
next = n;
}
}
private Node<E> head = null; //head node of list or null if empty
private Node<E> tail = null; // tail node of list or null if empty
private int size = 0; //size of list
public SinglyLinkedList(){} //constructs an initially empty list
public int size(){ //size getter
return size;
}
//accessors
public boolean isEmpty(){ //isList empty getter
return size ==0;
}
public E first(){ //head data getter
if(isEmpty()){
return null;
}
return head.getElement();
}
public E last(){ //tail data getter
if(isEmpty()){
return null;
}
return tail.getElement();
}
//updators
public void addFirst(E e){
head = new Node<>(e, head);
if(size == 0){
tail = head;
}
size++;
}
public void addLast(E e){
Node<E> newest = new Node<>(e, null);
if(isEmpty()){
head = newest;
}
else{
tail.setNext(newest);
}
tail = newest;
size++;
}
public E removeFirst(){
if(isEmpty()) return null;
E answer = head.getElement();
head = head.getNext();
size--;
if(size==0)
tail = null;
return answer;
}
}