import java.util.*; public class LinkedListADT { private Node first; int size=0; public LinkedListADT () { first = null; } public int getSize() { return size; } public void addToPosition(Object newData, int position) { if (isEmpty()) { first = new Node(newData, null); } else if (position > size) addToBack(newData); else if (position == 1) addToFront(newData); else { Node temp = new Node(newData,null); int current=1; Node stop = first; while(stop.next!=null) { if (current+1 != position) { current++; stop = stop.next; } else { temp.next = stop.next; stop.next = temp; break; } } } } public void addToFront(Object newData) { if (isEmpty()) { first = new Node(newData, null); } else { Node temp = new Node(newData,null); temp.next = first; first = temp; } size++; } public void addToBack(Object newData) { if (isEmpty()) first = new Node(newData, null); else { Node temp = new Node(newData,null); Node end = first; while(end.next!=null) { end = end.next; } end.next = temp; end = null; } size++; } public void removeFront() { if(!isEmpty()) { first = first.next; size--; } } public void removeBack() { Node current = first; if(!isEmpty()) { if (current.next != null) { while(current.next.next != null) { current = current.next; } current.next = null; }else { first = null; current = null; } size--; } } public boolean isEmpty() { return first == null; } public void clear() { first = null; size = 0; } public String getAllData() { String output = ""; Node temp = first; while(temp.next != null) { output += temp.data + "\n\n"; temp = temp.next; } output += temp.data + "\n\n"; return output; } private class Node { Object data; Node next; public Node (Object newData, Node newNext) { data = newData; next = newNext; } } public Iterator getIterator() { return new MyIterator(); } //iterator class for MyLinkedList private class MyIterator implements Iterator { //attribute - a ref to a current node in the list private Node current; private boolean endOfIteration; public MyIterator() { current = first; endOfIteration = false; } public boolean hasNext() { if(current == null) return false; else if(endOfIteration == true) return false; else return true; } public Object next() { if (!isEmpty()) { Object value; value = current.data; current = current.next; if (current == null) { endOfIteration = true; } return value; } else throw new NoSuchElementException(); } public void remove() { //how to implement this method } } }
I would like to ask how to implement a remove method in an iterator like this. need it for my college assignment, thx in advance. helps will be much appreciate!