在Java中迭代链接列表,直接在next()方法中过滤?

时间:2016-04-23 16:03:15

标签: java linked-list iterator

我在CS的一部分作业中遇到了一些问题。我需要用Java编写一个链表,然后用迭代器迭代奇数。实质上,forEach循环必须只迭代奇数。

到目前为止,我只在LinkedList类中使用它:

public class Iterator implements java.util.Iterator<Integer> {

    private Node nextNode;

    public Iterator(){
        nextNode = head_;
    }

    @Override
    public boolean hasNext() {
        return (nextNode != null);// && (nextNode.data_ % 2 != 0);
    }

    @Override
    public Integer next() {
        if (!hasNext()) throw new NoSuchElementException();
        Integer data = nextNode.data_;
        nextNode = nextNode.next_;
        return data;
    }

    public void remove(){
        throw new UnsupportedOperationException();
    }
}

public Iterator iterator() {
    return new Iterator();
}

如果我取消注释&& (nextNode.data_ % 2 != 0);,则仅打印第一个数字(恰好是不均匀的)。我也尝试在next()方法中实现它,但没有成功。

请给我一个提示,以便进一步尝试。

//稍后编辑:我没有提到我要过滤的链接列表包含随机数并且没有排序。

4 个答案:

答案 0 :(得分:2)

您的过滤器应位于.next方法内,而不是.hasNext。这是一个简单的逻辑:你遍历整个列表,hasNext必须一直返回true,除非当前元素是最后一个元素。

答案 1 :(得分:2)

编辑:如果您只想要奇数数据点,这应该是这样做的方法。我想我们假设你想要开始奇怪的索引。

function () {
                    socket.emit({action: 'a'});
                }

答案 2 :(得分:1)

你必须使用nextnode.next_两次才能获得奇数。这是因为你想跳过nextnode.next_,因为如果你当前的那个是奇数,它总是一个偶数。另外,你的hasnext需要检查两个空格

答案 3 :(得分:1)

我们应该查看Iterator.hasNextIterator.next

的官方文档

http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

对于hasNext,我们阅读了

  

如果迭代包含更多元素

,则返回true

内部结构无关紧要。所以我们别无选择,我们的实现必须检查整个链表,直到找到奇数元素或列表的结尾。另请注意,hasNext的来电不应更改您的结构。

public boolean hasNext() {
        Node tempNode = nextNode;   // nextNode need to stay the same
        while (tempNode != null){
            if (tempNode .data_ % 2 != 0){
                return true;
            }
            tempNode = tempNode._next;
        }
        // if we are here, we found no element that is odd
        return false;
    }

现在next方法几乎相同,这次我们需要推进内部nextNode。如果我们不这样做,调用者将始终获得相同的元素。

public Integer next() {
    while (nextNode != null){
            int data = nextNode.data;
            nextNode = nextNode.next_;
            if (data % 2 != 0){
                return data;
            }
    }
    //no odd element was found
    throw new NoSuchElementException();
}