S
S
Snikerssurgut2015-03-22 17:21:56
Java
Snikerssurgut, 2015-03-22 17:21:56

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

1 answer(s)
C
Cyril, 2015-03-22
@Snikerssurgut

Why not peek at the original?)
Implementation of the ListIterator iterator in Java from line 823
Of course, it's hard to look at the sources from the JDK out of habit, but this is a useful skill that will come in handy in the future.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question