Java订购双链表项目

时间:2011-12-03 16:17:00

标签: java data-structures

我的家庭作业有问题。作业是:

为有序的双向链表实现一个类。它应该是可迭代的。也就是说,它应该有一个iterator()方法,它返回一个Iterator类型的对象。您还应该实现迭代器本身。如有必要,创建另一个类。

除了这个类之外,还要实现一个驱动程序来测试它。驱动程序应该读取包含字符串的文件的名称,每行一个。然后它应该读入文件,将每个字符串添加到列表中。然后使用迭代器打印出结果列表,该列表应与排序顺序的文件内容相同。

到目前为止,我已对程序的所有部分进行了正确编译,但我无法使驱动程序正常工作。我到目前为止的代码是:

import java.util.Iterator;

public interface ListADT<T> extends Iterable<T>
{
    /**
     * Removes and returns the first element from this list.
     */
    public T removeFirst( );

    /**
     * Removes and returns the last element from this list.
     */
    public T removeLast( );

    /**
     * Removes and returns the specified element from this list.
     */
    public T remove(T element);

    /**
     * Returns a reference to the first element in this list.
     */
    public T first( );

    /**
     * Returns a reference to the last element in this list.
     */
    public T last( );

    /**
     * Returns true if this list contains the specified target element.
     */
    public boolean contains(T target);

    /**
     * Returns true if this list contains no elements.
     */
    public boolean isEmpty( );

    /**
     * Returns the number of elements in this list.
     */
    public int size( );

    /**
     * Returns an iterator for the elements in this list.
     */
    public Iterator<T> iterator( );

    /**
     * Returns a string representation of this list.
     */
    public String toString( );
}

public interface OrderedListADT<T> extends ListADT<T>
{
   /**
    * Adds the specified element to this list at the proper location.
    */
   public void add(T element);
}

import java.util.Iterator;

public class DoubleList<T> implements ListADT<T>
{
    protected DoubleNode<T> front, rear;
    protected int count;

    /**
     * Creates an empty list using the default capacity.
     */
    public DoubleList( )
    {
        rear = null;
        front = null;
        count = 0;
    }

    /**
     * Removes and returns the first element in the list.
     */
    public T removeFirst( ) throws EmptyCollectionException
    {
        if (isEmpty( ))
        {
            throw new EmptyCollectionException("list");
        }

        T result = front.getElement( );
        front = front.getNext( );

        if (front == null)
        {
            rear = null;
        }
        else
        {
            front.setPrevious(null);
        }

        count--;
        return result;
    }

    /**
     * Removes and returns the last element in the list.
     */
    public T removeLast( ) throws EmptyCollectionException
    {
        T result;

        if (isEmpty( ))
        {
            throw new EmptyCollectionException("list");
        }

        result = rear.getElement( );
        rear = rear.getPrevious( );

        if (rear == null)
        {
            front = null;
        }
        else
        {
            rear.setNext(null);
        }

        count--;

        return result;
    }

    /**
     * Removes and returns the specified element.
     */
    public T remove(T element) throws ElementNotFoundException
    {
        T result;
        DoubleNode<T> nodeptr = find(element);

        if (nodeptr == null)
        {
            throw new ElementNotFoundException("list");
        }

        result = nodeptr.getElement( );

        if (nodeptr == front)
        {
            result = this.removeFirst( );
        }
        else if (nodeptr == rear)
        {
            result = this.removeLast( );
        }
        else
        {
            nodeptr.getNext( ).setPrevious(nodeptr.getPrevious( ));
            nodeptr.getPrevious( ).setNext(nodeptr.getNext( ));
            count--;
        }

        return result;
    }

    /**
     * Returns a reference to the element at the front of the list.
     * The element is not removed from the list.  Throws an 
     * EmptyCollectionException if the list is empty.
     */
    public T first( ) throws EmptyCollectionException
    {
        if (isEmpty( ))
        {
            throw new EmptyCollectionException("list");
        }

        return front.getElement( );
    }

    /**
     * Returns a reference to the element at the rear of the list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.
     */
    public T last( ) throws EmptyCollectionException
    {
        if (isEmpty( ))
        {
            throw new EmptyCollectionException("list");
        }

        return rear.getElement( );
    }

    /**
     * Returns true if this list contains the specified element.
     */
    public boolean contains(T target)
    {
        return (find(target) != null);
    }

    /**
     * Returns a reference to the specified element, or null if it
     * is not found.
     */
    public DoubleNode<T> find(T target)
    {
        boolean found = false;
        DoubleNode<T> traverse = front;
        DoubleNode<T> result = null;

        if (! isEmpty( ))
        {
            while (! found && traverse != null)
            {
                if (target.equals(traverse.getElement( )))
                {
                    found = true;
                }
                else
                {
                    traverse = traverse.getNext( );
                }
            }
        }
        if (found)
        {
            result = traverse;
        }

        return result;
    }

    /**
     * Returns true if this list is empty and false otherwise.
     */
    public boolean isEmpty( )
    {
        return (count == 0);
    }

    /**
     * Returns the number of elements currently in this list.
     */
    public int size( )
    {
        return count;
    }

    /**
     * Returns an iterator for the elements currently in this list.
     */
    public Iterator<T> iterator( )
    {
        return new DoubleIterator<T>(front, count);
    }

    /**
     * Returns a string representation of this list.
     */
    public String toString( )
    {
        String result = "";
        DoubleNode<T> traverse = front;

        while (traverse != null)
        {
            result = result + (traverse.getElement( )).toString( ) + "\n";
            traverse = traverse.getNext( );
        }

        return result;
    }
}

public class DoubleOrderedList<T> extends DoubleList<T> implements OrderedListADT<T>
{
    /**
     * Creates an empty list using the default capacity.
     */
    public DoubleOrderedList( )
    {
        super( );
    }

    /**
     * Adds the specified element after the specified target element.
     * Throws a ClassCastException if the element is not Comparable.
     * Throws a ElementNotFoundException if the target is not found.
     */
    public void add(T element)
    {
        Comparable temp;

        temp = (Comparable)element;

        DoubleNode<T> traverse = front;
        DoubleNode<T> newnode = new DoubleNode<T>(element);
        boolean found = false;

        if (isEmpty( ))
        {
            front = newnode;
            rear = newnode;
        }
        else if (temp.compareTo(rear.getElement( )) >= 0)
        {
            rear.setNext(newnode);
            newnode.setPrevious(rear);
            newnode.setNext(null);
            rear = newnode;
        }
        else if (temp.compareTo(front.getElement( )) <= 0)
        {
            front.setPrevious(newnode);
            newnode.setNext(front);
            newnode.setPrevious(null);
            front = newnode;
        }
        else
        {
            while ((temp.compareTo(traverse.getElement( )) > 0))
            {
                traverse = traverse.getNext( );
            }

            newnode.setNext(traverse);
            newnode.setPrevious(traverse.getPrevious( ));
            traverse.getPrevious( ).setNext(newnode);
            traverse.setPrevious(newnode);
        }

        count++;
    }
}

import java.util.*;

public class DoubleIterator<T> implements Iterator
{
    private int count; //The number of elements in the collection.
    private DoubleNode<T> current; //The current position

    /**
     * Sets up this iterator using the specified items.
     */
    public DoubleIterator(DoubleNode<T> list, int size)
    {
        current = list;
        count = size;
    }

    /**
     * Returns true if this iterator has at least one more element
     * to deliver in the iteration.
     */
    public boolean hasNext( )
    {
        return (current != null);
    }

    /**
     * Returns the next element in the iteration.  If there are
     * no more elements in this iteration, a NoSuchElementException
     * is thrown
     */
    public T next( )
    {
        if (! hasNext( ))
        {
            throw new NoSuchElementException( );
        }

        T result = current.getElement( );
        current = current.getNext( );

        return result;
    }

    /**
     * The remove operation is not supported.
     */
    public void remove( ) throws UnsupportedOperationException
    {
        throw new UnsupportedOperationException( );
    }
}

public class DoubleNode<E>
{
    private DoubleNode<E> next;
    private E element;
    private DoubleNode<E> previous;

    /**
     * Creates an empty node.
     */
    public DoubleNode( )
    {
        next = null;
        element = null;
        previous = null;
    }

    /**
     * Creates a node storing the specified element.
     */
    public DoubleNode(E elem)
    {
        next = null;
        element = elem;
        previous = null;
    }

    /**
     * Returns the node that follows this one.
     */
    public DoubleNode<E> getNext( )
    {
        return next;
    }

    /**
     * Returns the node that precedes this one.
     */
    public DoubleNode<E> getPrevious( )
    {
        return previous;
    }

    /**
     * Sets the node that follows this one.
     */
    public void setNext(DoubleNode<E> dnode)
    {
        next = dnode;
    }

    /**
     * Sets the node that follows this one.
     */
    public void setPrevious(DoubleNode<E> dnode)
    {
        previous = dnode;
    }

    /**
     * Returns the element stored in this node.
     */
    public E getElement( )
    {
        return element;
    }

    /**
     * Sets the element stored in this node.
     */
    public void setElement(E elem)
    {
        element = elem;
    }
}


import java.util.*;
import java.io.*;

public class Driver
{
    public static void main(String[ ] args) throws IOException
    {
        Scanner keyboard = new Scanner(System.in); //Variable used for keyboard input.
        String entry; //Variable used for lines of text in the file.

        //Ask the user for the name of the file they want to use.
        System.out.print("Enter the name of the file: ");
        String filename = keyboard.nextLine( );

        //Check to see if the file exists.
        File file = new File(filename);

        //Runs if the filename entered is invalid or does not exist.
        if (!file.exists( ))
        {
            //Displays an error message if the file does not exist.
            System.out.println("The file " + filename + " does not exist.");

            //Exits the program.
            System.exit(0);
        }

        //Opens the file.
        Scanner inputFile = new Scanner(file);

        while (inputFile.hasNext( ))
        {
            entry = inputFile.nextLine( );
            DoubleOrderedList<String> doublyOrderedList = new DoubleOrderedList<String>( );

            doublyOrderedList.add(entry);
            doublyOrderedList.iterator( );


        }

        //Close the file when all processes have finished.
        inputFile.close( );
    }
}

我遇到的问题是让驱动程序在排序后打印出列表。我不是一个经验丰富或非常优秀的程序员,但我已经尝试了所有可能的选择,包括寻求相当擅长编程的同学的帮助。我还在程序员页面上多次询问,他们不愿意帮我解决我的问题。我不是要求任何人为我做这项工作,我只是想尽力解决这个问题,并且可以使用一双新的眼睛。

2 个答案:

答案 0 :(得分:2)

既然是作业,我会向你解释一下这些步骤 在这一行:doublyOrderedList.iterator( );您需要将返回值分配给您的Iterator(或DoubleIterator)。然后你拿走那个迭代器并遍历你的列表并在每个站点打印值。

答案 1 :(得分:0)

首先,看起来您正在为输入文件的每一行创建一个新列表,这似乎与您给出的赋值不一致:

    while (inputFile.hasNext( ))
    {
        entry = inputFile.nextLine( );
        DoubleOrderedList<String> doublyOrderedList = new DoubleOrderedList<String>( );

        doublyOrderedList.add(entry);
        doublyOrderedList.iterator( );


    }

您只想创建一次列表,然后在循环浏览文件时将输入文件的每一行添加到该列表中。

其次,在填充列表之后,您希望返回列表的迭代器,然后迭代它,打印迭代器返回的每个项目。现在你没有对迭代器做任何事情,只是返回它(同样,那个逻辑应该移到循环之外 - 它应该在填充列表之后完成。)

查看循环遍历迭代器的语法,并询问您可能遇到的任何具体问题。我认为这应该足以让你继续前进。