Answer the question
In order to leave comments, you need to log in
How to write your own methods for adding and removing an element in a LinkedList?
There is a task: reinvent the wheel , write your own listIterator. The main part of the methods turned out (of course, through one place), but the main 2 methods could not be written (constantly either errors or an endless list).
import java.util.*;
public class MyListIterator<T> implements ListIterator<T> {
private Node<T> cur;
private Node<T> prev;
private int index;
private boolean lastOpWasNext;
private boolean lastOpWasPrev;
MyListIterator(Node<T> head) {
cur = head;
prev = null;
index = 0;
}
public boolean hasNext() {
return cur != null;
}
public boolean hasPrevious() {
return prev != null;
}
public int nextIndex() {
return index;
}
public int previousIndex() {
return index-1;
}
public T next() throws NoSuchElementException {
if(!this.hasNext()) {
throw new NoSuchElementException();
}
prev = cur;
cur = cur.next;
lastOpWasNext = true;
lastOpWasPrev = false;
index++;
return prev.elem;
}
public T previous() throws NoSuchElementException{
if(!this.hasPrevious())
throw new NoSuchElementException();
cur = prev;
prev = prev.prev;
lastOpWasNext = false;
lastOpWasPrev = true;
index--;
return cur.elem;
}
public void add(T elem) throws IndexOutOfBoundsException {
// этот метод не получилось сделать
}
public void set(T elem) throws IllegalStateException {
Node<T> el = null;
if(lastOpWasNext) {
el = prev;
}
if(lastOpWasPrev) {
el = cur;
}
if(el == null) throw new IllegalStateException();
el.elem = elem;
}
public void remove() throws UnsupportedOperationException {
// и этот метод не получилось сделать
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question