循环链表和迭代器

时间:2016-02-11 06:14:05

标签: java linked-list iterator

我无法让我的迭代器实际工作并测试我的add和next方法。我想知道是否有人可以指出我错过了什么。我已经工作了一段时间,似乎无法弄清楚如何正确初始化对象,一直说无法解析为某种类型。谢谢 这是我的主要课程

public class CircularList<E> { 
private int size = 0;

//Inner Class
private static class Node<E>{
    private E data;
    private Node<E> next=null;
    private Node<E> previous=null;

    private Node(E dataItem) {
        data = dataItem;
    }
}


//Iterator
public class CircleIter implements ListIterator<E>{
    private Node<E> nextItem;
    private Node<E> lastItemReturned;
    private int index = 0;

public CircleIter(){
    nextItem=null;
    lastItemReturned=null;
}

@Override
public void add(E data) {
    Node<E> newNode = new Node<E>(data);
    if(index==0){
        newNode.next=newNode;
        newNode.previous=newNode;
        nextItem=newNode;
        lastItemReturned=newNode;
    }
    else{
        newNode.previous=nextItem.previous;
        nextItem.previous.next=newNode;
        newNode.next=nextItem;
        nextItem.previous=newNode;

    }
    index++;
    size++;
}

@Override
public boolean hasNext() {
    return nextItem != null;
}

@Override
public boolean hasPrevious() {
    return (lastItemReturned.next == null && size != 0)
            || lastItemReturned.previous != null;
}

@Override  //need to look over
public E next() {
   if (!hasNext()) {
        throw new NoSuchElementException();
   }
  lastItemReturned = nextItem;
  nextItem = nextItem.next;
  index++;
  return lastItemReturned.data;
}
@Override
public int nextIndex() {
    return index;
}

@Override //need to look over
public E previous() {
    nextItem=lastItemReturned;
    lastItemReturned=lastItemReturned.previous;
    index--;
    return nextItem.data;
}
@Override
public int previousIndex() {
    return index-1;
}

//remove last item returned through next&previous method
@Override
public void remove() {
      if (lastItemReturned == null) {
          throw new IllegalStateException();
        }
      nextItem.previous=lastItemReturned.previous;
      lastItemReturned.previous.next=nextItem;
      index--;
      size--;
      lastItemReturned = nextItem.previous;

}

@Override
public void set(E node) {
      if (lastItemReturned == null) {
          throw new IllegalStateException();
        }
        lastItemReturned.data = node;       
}

}  //end of iterator class

}

我的测试班

import CircularList.CircleIter;

public class CircularListTest {
public static void main(String[] args) {
    CircularList<Integer> intList = new CircularList<Integer>();

    CircleIter<Integer> iter= intList.CircleIter<Integer>();
    iter.add(5);


  }
}

1 个答案:

答案 0 :(得分:0)

如果要创建CircularList.CircleIter类的实例,则应使用运算符“new” CircularList.CircleIter是CircularList类的内部类(非静态嵌套类),因此为了创建它的新实例,您应该提供用special syntax封闭类的实例:
CircularList<Integer>.CircleIter iter = intList.new CircleIter();
通常集合公开迭代器创建的特殊方法(例如,List中的iterator()方法)以隐藏消费者的这种语法。
正如Alex Sou之前提到的那样,只有封闭的类在你的定义中被参数化。