Как связать двусвязный список и итератор? - PullRequest
0 голосов
/ 14 мая 2019

Я пытаюсь реализовать двусвязный список без использования интерфейса Iterable или Iterator. Так что в настоящее время у меня есть реализация, но я действительно не понимаю, как я могу подключить реализацию Итератора к списку. Как это должно работать, когда я не обращаюсь друг к другу с разбором одного из них в качестве аргумента для конструктора. Это очень глубокий вопрос для меня, потому что он подразумевает некоторые большие концепции Java. Буду очень признателен за вашу помощь.

Мои текущие решения:

package info2.list;

import java.util.NoSuchElementException;

import info2.MyCollection;
import info2.list.Doublylinkedlist.ListElem;

public class Doublylinkedlist_Iterator<E> {

    protected ListElem currentItem;
    private int currentIndex = 0;

    public Doublylinkedlist_Iterator(ListElem currentItem) {
        this.currentItem = currentItem;
    }

    public boolean hasNext() {
        if (!(this.currentItem.next == null))
            return true;
        else
            return false;
    }

    public boolean hasPrevious() {
        if (!(this.currentItem.previous == null))
            return true;
        else
            return false;
    }

    public E next() throws NoSuchElementException { // Warum wurde dieser Datentyp als Parameter definiert?
        if (!this.hasNext())
            throw new NoSuchElementException("Es gibt kein nächstes Element.");
        E tmp = (E) currentItem; // MUss das hier den Inhalt/Value vom CurrentItem returnen? Is that properly
                                    // solved? Warum funktioniert es nicht mit ListElem? Welche Typenkonvertierugn
                                    // ist hier adaquat?
        currentItem = this.currentItem.next;
        currentIndex++;
        return tmp;
    }

    public E previous() throws NoSuchElementException {
        if (!this.hasPrevious())
            throw new NoSuchElementException();
        E tmp = (E) currentItem;
        currentItem = this.currentItem.previous;
        currentIndex--;
        return tmp;
    }
}

Вот моя реализация Doubly-Linked-List, которая до сих пор не завершена. Я добавлю завершенную версию, когда моя проблема будет решена.

package info2.list;

import java.util.ArrayList;

import info2.MyCollection;
import info2.list.Doublylinkedlist_Iterator;

public class Doublylinkedlist<E> {

    /*
     * Anonyme Innere Klasse
     */
    protected class ListElem {
        ListElem next;
        ListElem previous;
        E content;

        ListElem(E content, ListElem next, ListElem previous) {
            this.content = content;
            this.next = next;
            this.previous = previous;
        }

        protected ListElem getNext() {
            return this.next;
        }

        protected ListElem getPrevious() {
            return this.previous;
        }

        protected E getContent() {
            return this.content;
        }
    }

    // Normaleweise muesste die Anzahl der ITertoren einer Liste auch auf diese 2
    // beschränkt werden, sodasss man immer ausschließlich zwei Iteratoren hat
    protected Doublylinkedlist_Iterator<E> head;
    protected Doublylinkedlist_Iterator<E> tail;
    private int length;

    public Doublylinkedlist() {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }

    public Doublylinkedlist_Iterator getIterator() {
        return new Doublylinkedlist_Iterator(this);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...