1

リンク付きのリスト インターフェイスを実装していますが、「ListADT」は Iterable インターフェイスを実装しているためです。そのため、方法がわからないイテレータを生成するメソッドが必要です。そのまま使ってみたのですが、リンクリスト用のオブジェクトを作成して iterator() メソッドを呼び出すとオーバーフローしてしまいます。メソッドが Iterator オブジェクトを生成することになっていることは知っていますが、その方法はわかりません。

import java.util.Iterator;

public class LinkedList<T> implements ListADT<T> 
{ 
protected int count;
protected LinearNode <T> head, tail;
private  int modCount;

public LinkedList()
{
    count =0;
    head = tail= null;
}

 public T removeFirst()
 {
     T result = head.getElement();
     head = head.getNext();
     count--;
     return result;

 }

 public T removeLast()
 {
     // THROW EMPTY EXCEPTION

     T result;
     LinearNode <T> previous = null;
     LinearNode <T> current = head;
     while(!current.equals(tail))
     {
         previous = current;
         current = current.getNext();
     }
     result = tail.getElement();
     tail = previous;
     tail.setNext(null);
     count--;
     return result;

 }

 public T remove(T element)
 {
     // throw exception

     boolean found = false;
     LinearNode <T> previous = null;
     LinearNode <T> current = head;

     while (current != null && !found)
     {
         if(element.equals(current.getElement()))
             found = true;
         else
         {
             previous = current;
             current = current.getNext();
         }

         if (!found)
         {

         }
         else if (current.equals(head))
         {
             head = current.getNext();
         }
         else if(current.equals(tail))
         {
             tail = previous;
             tail.setNext(null);
         }
         else
             previous.setNext(current.getNext());
     }
     count --;
     return current.getElement();
 }

 public T first()
 {
    return head.getElement(); 
 }

 public T last()
 {
     return tail.getElement();
 }

 public boolean contains(T target)
 {
     boolean found = false;
     LinearNode <T> previous = null;
     LinearNode <T> current = head;

     while (current != null && !found)
     {
         if(target.equals(current.getElement()))
             found = true;
         else
         {
             previous = current;
             current = current.getNext();
         }
     }
     return found;
 }

 public boolean isEmpty()
 {
     boolean result = false;
     if( head == null && tail ==null)
     {
         result = true;
     }
     return result;
 }

 public int size()
 {
     return count;
 }

 public Iterator<T> iterator()
 {

    return this.iterator();
 }

 public String toString()
 {
     LinearNode <T> current = head;
     String result ="";
     String line = "";
     int loopCount=0;
     while(current != null)
     {
         loopCount++;
         line = loopCount + "> " + (String) current.getElement() + "\n";
         result = result + line;
         current = current.getNext();
     }
     return result;
 }
} 
4

1 に答える 1