4

我需要您查看我对单链表 (SLL) 的实现。实现应该使用泛型并且能够使用增强的for。

问题是,当我for (Number n : list)成为or时,我收到错误:“类型不匹配:无法从元素类型对象转换为数字”。listMyLinkedList<Integer>MyLinkedList<Double>

这就是我所拥有的。我不太确定的部分是泛型和迭代器。

提前致谢。

import java.util.Iterator;

public class MyLinkedList<T> implements Iterable<Object>
{
    private Node head;

    public MyLinkedList ()
    {
        head = null;
    }

    public void add (Node n)
    {
        if (head == null)
        {
            head = n;
        }

        else
        {
            Node node = head;
            while (node.next != null) 
            {
                node = node.next;
            }
            node = n;
        }
    }

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

    public int size () 
    {
        int ret = 0;
        MyLinkedListIterator it = new MyLinkedListIterator (head);
        while (it.hasNext ())
        {
            it.next();
            ret++;
        }

        return ret;
    }

    public Node getHead ()
    {
        return head;
    }
}

class MyLinkedListIterator<T> implements Iterator
{
    private Node node;

    public MyLinkedListIterator (Node h)
    {
        node = h;
    }

    public MyLinkedListIterator (MyLinkedList<T> l)
    {
        this(l.getHead ());
    }

    public boolean hasNext () 
    {
        if (node.next == null)
        {
            return false;
        }

        else
        {
            return true;
        }
    }

    public Object next () 
    {
        return node.next;
    }

    public void remove () 
    {

    }   
}
4

5 回答 5

8
  • 你应该有Iterable<T>而不是Iterable<Object>.
  • add(Node)实际上并没有将对象添加到列表中。
  • MyLinkedListIterator<T>应该实施Iterator<T>
  • MyLinkedListIterator.hasNext()NullPointerException如果列表为空,将抛出一个。
  • MyLinkedListIterator.next()不会移动到列表中的下一个项目。
于 2010-09-26T21:33:44.447 回答
2

Iterator<T>您应该从该方法返回一个,iterator并且还应该扩展Iterable<T>而不是Iterable<Object>.

此外,您MyLinkedListIterator<T>应该实施Iterator<T>. 然后它应该工作。

于 2010-09-26T21:25:52.170 回答
1

你为什么不使用<E>

public class Node<E>{
 E data;
 Node<E> next;
}

public class SinglyLinkedList<E> {

 Node<E> start;
 int size;
 .......
}

在这里寻找一个全面的实施

于 2010-09-26T21:33:57.010 回答
1

除了其他人所说的之外,您可能不应该Node在公共方法中公开 - 节点应该是实现的纯粹内部方面。

于 2010-09-27T07:16:13.040 回答
0

扩展要点: MyLinkedListIterator.next() 不会移动到列表中的下一项。

下一个方法应该是这样的,以使其工作:

public T next() {
    if(isFirstNode) {
        isFirstNode = false;
        return node.data;
    }
    node = node.next;
    return node.data;
}
于 2013-10-13T20:59:57.993 回答