/**
* A simple singly linked list, without tail pointer.
* Naming follows Morelli, more or less.
*
* @author <a href="mailto:bremner@unb.ca">David Bremner</a>
* @version 1.0
*/
public class List<T>{
private Node<T> head;
public List(){
head=null;
}
public void insertFirst(T o){
Node<T> node=new Node<T>(o);
node.setNext(head);
head=node;
}
public void insertLast(T o){
Node<T> node=new Node<T>(o);
if (head==null){
head=node;
} else {
Node<T> current=head;
while(current.getNext()!=null){
current=current.getNext();
}
current.setNext(node);
}
}
public void print(){
for (Node<T> current=head; current!=null;
current=current.getNext()){
current.print();
}
}
public boolean isEmpty(){
return (head==null);
}
public T removeFirst(){
if (head==null)
throw new
IllegalArgumentException(
"No first element");
T retVal=head.getData();
head=head.getNext();
return retVal;
}
public void removeLast(){
if (head==null)
throw new IllegalArgumentException("Empty");
Node<T> current=head, previous=null;
while(current.getNext()!=null){
previous=current;
current=current.getNext();
}
if (previous != null)
previous.setNext(null);
else
head = null;
}
public static void main(String[] args){
List<String> test=new List<>();
test.insertLast("hello");
test.insertFirst("goodbye");
test.insertLast("are you still here");
test.print();
System.out.println("");
test.removeFirst();
test.print();
System.out.println("");
test.removeLast();
test.print();
System.out.println("");
test.removeLast();
test.print();
}
}
//