//The Node class
//=======================//
public class Node<E>{
private E value;
private Node<E> next;
public Node(E initValue, Node<E> initNext){
value = initValue;
next = initNext;
}
public E getValue(){
return value;
}
public Node<E> getNext(){
return next;
}
public void setValue(E newValue){
value = newValue;
}
public void setNext(Node<E> newNext){
next = newNext;
}
}
//The SinglyLinkedList class
//=======================//
import java.util.NoSuchElementException;
public class SinglyLinkedList<E>{
private Node<E> head;
//Construct an empty LinkedList
public SinglyLinkedList(){
head = null;
}
//return true if the LinkedList is empty
public boolean isEmpty(){
return head == null;
}
//return the first element in the LinkedList
public E getFirst(){
if(head == null){
throw new NoSuchElementException();
}else{
return head.getValue();
}
}
//return the last element in the LinkedList
public E getLast(){
if(head == null){
throw new NoSuchElementException();
}else{
Node<E> tempNode = head;
while(tempNode.getNext() != null){
tempNode = tempNode.getNext();
}
return tempNode.getValue();
}
}
//Insert a new element at the beginning of the LinkedList
public void addFirst(E value){
head = new Node<E>(value, head);
}
//Insert a new Node at the end of the LinkedList
public void add(E value){
if(head == null){
addFirst(value);
}else{
Node<E> tempNode = head;
while(tempNode.getNext() != null){
tempNode = tempNode.getNext();
}
tempNode.setNext(new Node<E>(value, null));
}
}
//remove and return the first element in the LinkedList; throw NoSuchElementException if this list is empty
public E removeFirst(){
if(head == null){
throw new NoSuchElementException();
}else{
E tempValue = head.getValue();
head = head.getNext();
return tempValue;
}
}
//remove and return the last element in the LinkedList; throw NoSuchElementException if this list is empty
public E removeLast(){
if(head == null){
throw new NoSuchElementException();
}else{
Node<E> tempNode = head;
while(tempNode.getNext() != null){
tempNode = tempNode.getNext();
}
E tempValue = tempNode.getValue();
tempNode = null;
return tempValue;
}
}
//remove all elements
public void clear(){
head = null;
}
//return a list of elements such as [3,4,5]
public String toString(){
String result = "[";
Node<E> tempNode = head;
while(tempNode != null){
result += tempNode.getValue();
if(tempNode.getNext() != null){
result += ",";
}
tempNode = tempNode.getNext();
}
return result + "]";
}
//More Methods to be added
}