【问题标题】:How to print out data using java iterator with a linked list如何使用带有链表的java迭代器打印数据
【发布时间】:2021-11-26 03:42:53
【问题描述】:

我正在尝试使用我创建的 MyLinkedListIterator 类迭代 MylinkedList。我希望它能够打印出 drop、goofy、Donald、Duck、Mouse 等……但是我编写的 while 循环无法正常工作。我尝试通过 system.out.print(iter.next()) 进行调试,期望第一个元素打印在链表“drop”中,但返回 null。

public class xxx_xxx_xxxx{
    
        public static void main(String[] args) throws Exception {
    
            
            MyLinkedList<String> list = new MyLinkedList<>();
    
            list.add("drop");
            list.add("goofy");
            list.add("Donald");
            list.add("Duck");
            list.add("Mouse");
            list.add("Kangaroo");
            list.add("Koala");
            // initialized list of MyLinkedListIterator
            MyLinkedListIterator<String> iter = new MyLinkedListIterator<String>();
    
            while (iter.hasNext()) {
                System.out.print(iter.next());
            }
    
        }
    
    }
    
    interface MyList<E> {
    
        public void insert(int index, E object) throws Exception;
    
        public void add(E object);
    
        public E get(int index) throws Exception;
    
        public int indexOf(E object);
    
        public int lastIndexOf(E object);
    
        public E remove(int index) throws Exception;
    
        public E set(int index, E object) throws Exception;
    
        public int size();
    
    }
    
    class Node<E> {
        E element;
        Node<E> next;
    
        public Node(E element) {
            this.element = element;
        }
    }
    
    class MyLinkedList<E> implements MyList<E>, Iterator<E> {
        Node<E> head = null;
        Node<E> tail = null;
        int size = 0;
    
        @Override
        public void insert(int index, E object) throws Exception {
            if (index < 0 || index > size - 1)
                throw new Exception("Invalid index.");
    
            Node<E> newNode = new Node<>(object);
    
            Node<E> current = head;
            int counter = 0;
            Node<E> previous = null;
            while (counter < index) {
                previous = current;
                current = current.next;
                counter++;
            }
    
            if (previous != null)
                previous.next = newNode;
            newNode.next = current;
    
            size++;
    
            if (index == 0)
                head = newNode;
            if (index == size - 1)
                tail = newNode;
    
        }
    
        @Override
        public void add(E object) {
            Node<E> newNode = new Node<E>(object);
    
            size++;
    
            if (head == null)
                head = newNode;
            else
                tail.next = newNode;
            tail = newNode;
    
        }
    
        @Override
        public E get(int index) throws Exception {
            if (index < 0 || index > size - 1)
                throw new Exception("Invalid index.");
    
            Node<E> current = head;
            int counter = 0;
            while (counter < index) {
                current = current.next;
                counter++;
            }
    
            return current.element;
        }
    
        @Override
        public int indexOf(E object) {
            Node<E> current = head;
            int index = 0;
            while (current != null) {
                if (object.equals(current.element))
                    return index;
                current = current.next;
                index++;
            }
            return -1;
        }
    
        @Override
        public int lastIndexOf(E object) {
    
            int result = -1;
            Node<E> current = head;
            int index = 0;
            while (current != null) {
                if (object.equals(current.element))
                    result = index;
                current = current.next;
                index++;
            }
    
            return result;
        }
    
        @Override
        public E remove(int index) throws Exception {
            if (index < 0 || index > size - 1)
                throw new Exception("Invalid index.");
    
            Node<E> current = head;
            int counter = 0;
            Node<E> previous = null;
            while (counter < index) {
    
                previous = current;
                current = current.next;
                counter++;
            }
    
            if (previous != null)
                previous.next = current.next;
            E result = current.element;
    
            size--;
    
            if (index == 0)
                head = current.next;
            if (index == size - 1)
                tail = previous;
    
            return result;
        }
    
        @Override
        public E set(int index, E object) throws Exception {
            if (index < 0 || index > size - 1)
                throw new Exception("Invalid index.");
    
            Node<E> current = head;
            int counter = 0;
            while (counter < index) {
                current = current.next;
                counter++;
    
            }
    
            E result = current.element;
            current.element = object;
            return result;
    
        }
    
        @Override
        public int size() {
            // TODO Auto-generated method stub
            return size;
        }
    
        public Iterator<E> iterator() {
            // TODO Auto-generated method stub
            return new MyLinkedListIterator();
        }
    
        @Override
        public String toString() {
    
            String result = "[";
            Node<E> current = head;
            while (current != null) {
    
                result += current.element;
                if (current.next != null)
                    result += ", ";
    
                current = current.next;
            }
            return result + "]";
        }
    
        @Override
        public boolean hasNext() {
            // TODO Auto-generated method stub
            return false;
        }
    
        @Override
        public E next() {
            // TODO Auto-generated method stub
            return null;
        }
    }
    
    //Create the class MyLinkedListIterator<E>, which implements the Iterator<E> interface.
    
    class MyLinkedListIterator<E> implements Iterator<E> {
    
        // MyLinkedListIterator should contain the following data items,
    
        // "list" of type MyLinkedList
        MyLinkedList<E> list = new MyLinkedList<>();
    
        // "currentNode" of type Node<E>, initially set to list.head
        Node<E> currentNode = list.head;
    
        // The hasNext() method should return true as long as currentNode is not null
    
        public boolean hasNext() {
    
            return currentNode != null;
    
        }
    
        // The next() method should return the list's data item at currentNode, and
        // advance currentNode
    
        public E next() {
    
            Node<E> res = list.head;
            currentNode = list.tail;
            return (E) res;
    
        }
    
    }

【问题讨论】:

  • 您的代码中发生的事情太多,根本无法正常工作。您要实现什么,您是否只是在自己实现链表?如果是这样,那么除了对下面的答案评论的更正之外,MyLinkedList 不应该实现Iterator,而是应该实现Iterable?只有MyLinkedListIterator&lt;E&gt; 应该实现Iterator&lt;E&gt;。在此处查看实现迭代器如何工作的示例:gist.github.com/jnwhiteh/68d095c630dfcaddffd1

标签: java linked-list iterator


【解决方案1】:

next() 存在几个问题。您立即将currentNode 设置到列表的最后一个,如果我猜对了,这可能就是为什么您将 null 作为第二个元素的原因。

currentNode = list.tail;

考虑一下。你有一个链表。当前元素之后的 next 元素是什么?不是尾巴……

【讨论】:

  • 如果这个答案是新手,我很抱歉,但它会是 currentNode.next 吗?
  • 是的,下一个方法应该有currentNode = currentNode.next;。这行也是有问题的Node&lt;E&gt; res = list.head;,并且会导致下一个方法总是返回list.head,而是应该改为Node&lt;E&gt; res = currentNode;以返回迭代器的当前节点。
  • 你太棒了,谢谢!
  • @AndrewAmirzadeh 请注意,MyLinkedListIterator&lt;String&gt; iter = new MyLinkedListIterator&lt;String&gt;(); 这一行只是创建了一个没有列表/元素的新迭代器。它不会以任何方式与您的列表绑定,因此它将始终返回 null,因为您创建了一个内部空列表 MyLinkedList&lt;E&gt; list = new MyLinkedList&lt;&gt;(); 而不是尝试 MyLinkedListIterator&lt;String&gt; iter = list.iterator();
  • 我一直在进行所有修复,现在我得到了这个:无法读取字段“next”,因为“this.currentNode”为空。我需要做一个构造函数吗?我认为默认情况下,构造函数是由一个空白组成的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 2018-10-03
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多