Implement this java method public void addE item The method
Implement this java method, public void add(E item). The method behaves like this: when the input does not exist in the linked list, add it at the front; otherwise remove the existing one from the list and reinsert it to the front.
Solution
import java.util.Iterator;
public class LinkedList<E> extends AbstractList<E> {
    private ListNode front; // refers to first node in list (null if empty)
   
    // Constructs a new empty list.
    public LinkedList() {
        front = null; // null front means empty
    }
   
   public void add(int index, E value) {
        if (index == 0) {
            // insert at the front
            front = new ListNode(value, front);
        } else {
            // insert in middle/end; walk to node before the one to insert
            ListNode current = goTo(index - 1);
            ListNode newNode = new ListNode(value, current.next);
            current.next = newNode;
           
            // shorter version of the above code
            // current.next = new ListNode(value, current.next);
        }
    }
   
   public void remove(int index) {
        if (index == 0) {
            // removing from the front
            front = front.next;
        } else {
            ListNode current = goTo(index - 1);
            current.next = current.next.next; // deletes the node
        }
    }
   public void set(int index, E value) {
        ListNode current = goTo(index);
        current.data = value;
    }
   
   private class LinkedListIterator implements Iterator<E> {
        private ListNode current; // current position in list
       public LinkedListIterator() {
            current = front;
        }
       public boolean hasNext() {
            return current != null;
        }
       public E next() {
            E result = current.data;
            current = current.next;
            return result;
        }
       // not implemented for now
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }  
 }


