简体   繁体   English

Java Iterator中的单链接列表实现

[英]Singly Linked List implementation in Java Iterator

I'm writing a simple implementation of a Bag in Java. 我正在用Java写一个Bag的简单实现。 I am implementing Iterable and writing my own LinkedList Iterator. 我正在实现Iterable并编写自己的LinkedList Iterator。 So I'm racking my brain; 所以我在绞尽脑汁。 I am trying to add elements to the linked list. 我正在尝试将元素添加到链接列表。 I have a working implementation (the commented out code in the add() function). 我有一个可行的实现( add()函数中注释掉的代码)。 However, I do not understand why the following code does not work: 但是,我不明白为什么以下代码不起作用:

current.item = item;
Node<T> nextNode = new Node<T>();
current.next = nextNode;
current = nextNode;

So, given that the list is empty and the current head is initialized but has no item or next: I assign item to the current item, create a new node, set it to the current's next and change the current (head) to the node I just created. 因此,鉴于列表为空且当前头已初始化但没有项目或下一个项目:我将项目分配给当前项目,创建一个新节点,将其设置为当前项目的下一个节点,并将当前(头)更改为该节点我刚创建。 Adding two items to the list, I printed out the objects for posterity: 将两个项目添加到列表中,我打印出了后代对象:

current: Bag$Node@4524411f next: Bag$Node@401e7803 当前:Bag $ Node @ 4524411f下一个: Bag $ Node @ 401e7803

current: Bag$Node@401e7803 next: Bag$Node@10dba097 当前: Bag $ Node @ 401e7803下一个:Bag $ Node @ 10dba097

current: Bag$Node@10dba097 next: Bag$Node@1786f9d5 当前:Bag $ Node @ 10dba097下一个: Bag $ Node @ 1786f9d5

current: Bag$Node@1786f9d5 next: Bag$Node@704d6e83 当前: Bag $ Node @ 1786f9d5下一个:Bag $ Node @ 704d6e83

It looks clearly, to me at least, that the next is getting set with a new node each time just fine. 至少对我而言,很明显,每次都很好地设置下一个新节点。 I get all four elements added to the bag, but the item is lost and returns null for each index. 我将所有四个元素添加到包中,但是该项目丢失了,并且每个索引返回null。 The toArray() function shows [null, null, null, null] toArray()函数显示[null, null, null, null]

I'm sure it's something blindingly simple. 我敢肯定这很简单。 Below is the entire implementation. 以下是整个实现。

import java.util.Iterator;

public class Bag<T> implements Iterable<T> {
    private Node current;
    //Node<T> head;
    private int numberofProducts;
    T[] myBag;
    int defaultCapacity;

    public Iterator<T> iterator() {
        return new ListIterator<T>(current);
    }

    public Bag(int defaultCapacity) {
        this.current = new Node<T>();
        this.numberofProducts = 0;
        this.defaultCapacity = defaultCapacity;
    }

    public void add(T item) {
        if(isFull()) {
            System.out.println("bags full, yo");
            return;
        }

        current.item = item;
        Node<T> nextNode = new Node<T>();
        current.next = nextNode;
        current = nextNode;

        numberofProducts++;

    //Node<T> nextNode = current;
    //current = new Node<T>();
    //current.item = item;
    //current.next = nextNode;
    //numberofProducts++;


    }

    public Object[] toArray() {
        Object[] array = new Object[size()];

        int i = 0;
        Node<T> node = current;
        //Node<T> node = head;
        while(node.next != null) {
            array[i] = node.item;
            node = node.next;
            i++;
        }

        return array;
    }

    public boolean isEmpty() {
        return this.numberofProducts <= 0;
    }

    public boolean isFull() {
        return this.numberofProducts >= defaultCapacity;
    }

    public int size() {
        return this.numberofProducts;
    }

    private class Node<T> {
        private T item;
        private Node<T> next;
    }


    private class ListIterator<T> implements Iterator<T> {

        private Node<T> current;

        public  ListIterator(Node<T> first) {
            current = first;
        }

        public boolean hasNext() {

            return current != null;
        }

        public T next() {
            if(hasNext()) {
                T item = current.item;
                current = current.next;
                return item;
            }
            return null;
        }

        public void remove() {

        }
    }
}

The item values aren't lost. 项目值不会丢失。 The problem is that you lose track of the head of the linked list. 问题在于您无法跟踪链接列表的标题。 Your current variable keeps track of the tail already, and since your toArray() method starts at current , the while loop never executes because there are no elements after the tail element of the list. 您的current变量已经在跟踪尾部,并且由于toArray()方法从current开始,因此while循环永远不会执行,因为列表的tail元素之后没有任何元素。

Consequently, you just end up with an array of default-initialized Object values, ie null . 因此,您仅得到一个默认初始化的Object值数组,即null

To fix this, you need another instance variable to keep track of the head of the list, and this is what you'll use in your toArray() method. 要解决此问题,您需要另一个实例变量来跟踪列表的开头,这就是您将在toArray()方法中使用的变量。

From what I can see, the reason it's not acting as a Linked List is because you are not retaining a reference to the first element added. 据我所知,它不充当链接列表的原因是因为您没有保留对添加的第一个元素的引用。 Rather you retain a reference to the last ( current ) element added. 而是保留对添加的最后一个( current )元素的引用。

You can resolve this by adding a class field reference the first element added T head 您可以通过在第一个元素中添加T head添加类字段引用来解决此问题

Then in your add() method, set head to the Node you create. 然后在add()方法中,将head设置为您创建的Node Then when you construct your ListIterator, pass head as the parameter. 然后,在构造ListIterator时,将head作为参数传递。

You can change add(T item) to showing like this: 您可以将add(T item)更改为如下所示:

public void add(T item) {
    if (!isFull()) {
        Node<T> toAdd = new Node<>();
        toAdd.item = item;
        current.next = toAdd;
        current = toAdd;
        if (head == null) {
            head = toAdd;
        }
    }
}

Then add the class field Node<T> head to your Bag<T> class. 然后将类字段Node<T> headBag<T>类中。

Additionally, I'm not sure why Node is a static class, plus a number of other changes I won't get into now, but I guess the class is incomplete at present. 另外,我不确定为什么Node是一个静态类,以及我现在不打算进行的其他许多更改,但是我想该类目前还不完整。

The problem is with your logic written in the add() method. 问题出在用add()方法编写的逻辑上。 Whenever adding the new data to Bag, your root node is changing and pointing to the last node of your Bag. 每当将新数据添加到Bag时,您的根节点都会更改,并指向Bag的最后一个节点。 Since the next to last node is null, that's why the iterator is not returning anything. 由于倒数第二个节点为null,因此迭代器不返回任何内容。 Refer to this link for the exact solution. 请参考此链接以获取确切的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM