Реализация итераторов с двумя связанными списками при сложении / вычитании многочленов - PullRequest
0 голосов
/ 30 сентября 2018

У меня был вопрос по этому фрагменту кода, который я пытаюсь проработать.У меня есть подсказка: лучше объяснить это:

Представлять многочлен в виде упорядоченного списка терминов, где члены упорядочены по показателям в порядке убывания.Чтобы добавить два полинома, вы пересекаете оба списка и исследуете два термина в текущих позициях итератора, создавая третий список.Если показатель одного меньше, чем показатель другого, то вставьте больший в результат и добавьте итератор списка.Если показатели равны, то создайте новый член с этим показателем и суммой коэффициентов и продвиньте оба итератора.Например:

3x4 - 2x2 + 3x + 7 добавлено к 2x3 + 4x - 5 равно 3x4 + 2x3 - 2x2 + 7x + 2

Напишите программу для чтения и добавления полиномов.Вы должны определить класс Term, который содержит показатель степени и коэффициент.Этот класс должен реализовывать интерфейс Comparable, сравнивая значения показателей.

Продемонстрируйте свою программу, сначала создав три различных полинома, скажем, A, B и C, каждый из которых содержит не менее трехРазные термины объектов.Показать получающиеся полиномы для

A + B
B + C
A + C
A + B + C (Formatting issues)

В выходных данных вашей программы используйте этот метод для печати полиномов A, B и C, а затем распечатайте полученные полиномы с четырьмя суммамизапрошено выше

Что у меня есть

Основной класс:

public class Main{

public static void main(String[] args)
{
    // instance variables
    Term t1 = new Term(3, 4);
    Term t2 = new Term(-2,2);
    Term t3 = new Term(3,1);
    Term t4 = new Term(7,0);
    // 2x3 + 4x - 5
    //3x^4 - 2x^2 + 3x + 7
    Term t5 = new Term(2, 3);
    Term t6 = new Term(4,1);
    Term t7 = new Term(-5,0);


    KWLinkedList<Term> termList1 = new KWLinkedList<>();
    KWLinkedList<Term> termList2 = new KWLinkedList<>();
    KWLinkedList<Term> result = new KWLinkedList<>();
    termList1.add(t1);
    termList1.add(t2);
    termList1.add(t3);
    termList1.add(t4);

    termList2.add(t5);
    termList2.add(t6);
    termList2.add(t7);
    // 3x4 + 2x3 - 2x2 + 7x + 2
    result = addition(termList1, termList2);

    print(termList1);
    print(termList2);
    print(result);


                        //3x4 + 2x3 - 2x2 + 7x + 2 RESULT
    // print(termList1);



}

public static KWLinkedList<Term> addition (KWLinkedList<Term> listA, KWLinkedList<Term> listB)
{
    Iterator<Term> firstIterator = listA.listIterator(0);
    Iterator<Term> secondIterator = listB.listIterator(0);
    KWLinkedList<Term> result = new KWLinkedList<Term>();

    Term temp1;
    Term temp2;
    boolean firstRun = true;

    temp1 = firstIterator.next();
    temp2 = secondIterator.next();


    while((temp1 != null && temp2 != null) || firstRun)
    {
        try
        {
            firstRun = false;
            if (temp1.compareTo(temp2) == 0)
            {
                System.out.println("Adding: " + temp1 + " " +  temp2);

                result.add(new Term(temp1.getCoefficent() + temp2.getCoefficent(),
                        temp1.getExponent()));



                 if(firstIterator.hasNext())
                {
                    temp1 = firstIterator.next();
                }
                if(secondIterator.hasNext())
                {
                    temp2 = secondIterator.next();
                }
            }
            else if (temp1.compareTo(temp2) < 0)
            {
                result.add(temp2);
                if(secondIterator.hasNext())
                {
                    temp2 = secondIterator.next();
                }
            }
            else
            {
                result.add(temp1);
                if(firstIterator.hasNext())
                {
                    temp1 = firstIterator.next();
                }
            }
        }
        catch(Exception e)
        {
            e.getMessage();
        }

    }

    if(firstIterator.hasNext())
    {
        while(firstIterator.hasNext())
        {
            temp1 = firstIterator.next();

            result.add(temp1);
        }
    }
    if(secondIterator.hasNext())
    {
        while(secondIterator.hasNext())
        {
            temp2 = secondIterator.next();

            result.add(temp2);
        }
    }

    return result;

}

public static KWLinkedList<Term> subtraction(KWLinkedList<Term> listA, KWLinkedList<Term> listB)
{
    Iterator<Term> firstIterator = listA.listIterator(0);
    Iterator<Term> secondIterator = listB.listIterator(0);
    KWLinkedList<Term> result = new KWLinkedList<Term>();

    Term temp1;
    Term temp2;

    boolean firstRun = true;

    temp1 = firstIterator.next();
    temp2 = secondIterator.next();

    while((firstIterator.hasNext() && secondIterator.hasNext()) || firstRun)
    {
        try
        {
            firstRun = false;
            if (temp1.compareTo(temp2) == 0)
            {

                result.add(new Term(temp1.getCoefficent() - temp2.getCoefficent(),
                        temp1.getExponent()));
                temp1 = firstIterator.next();
                temp2 = secondIterator.next();
            }
            else if (temp1.compareTo(temp2) < 0)
            {
                result.add(new Term(temp2.getCoefficent() * -1, temp2.getExponent()));
                temp2 = secondIterator.next();
            }
            else
            {
                result.add(temp1);
                temp1 = firstIterator.next();
            }
        }
        catch(Exception e)
        {
            e.getMessage();
        }
    }

    if(firstIterator.hasNext())
    {
        while(firstIterator.hasNext())
        {
            temp1 = firstIterator.next();

            result.add(temp1);
        }
    }
    if(secondIterator.hasNext())
    {
        while(secondIterator.hasNext())
        {
            temp2 = secondIterator.next();

            result.add(new Term(temp2.getCoefficent() * -1, temp2.getExponent()));
        }
    }

    return result;
}

public static void print(KWLinkedList<Term> printList)
{

    Iterator<Term> printIterator = printList.listIterator(0);
    while (printIterator.hasNext())
    {

        System.out.print(printIterator.next() + " ");

    }
    System.out.println();
}}

Класс терминов:

public class Term implements Comparable <Term>{
 // instance variables
 private int coefficent = 0;
 private int exponent = 0;


public Term()
{
    coefficent = 0;
    exponent = 0;
}

public Term(int passedCoefficent, int passedExponet)
{
    setCoefficent(passedCoefficent);
    setExponent(passedExponet);
}

public void setCoefficent(int passedCoefficent)
{

    coefficent = passedCoefficent;
}
public void setExponent(int passedExponet)
{

    exponent = passedExponet;
}

public int getCoefficent()
{
    return coefficent;
}
public int getExponent()
{
    return exponent;
}

public String toString()
{
    if(exponent != 0)
    {
        return coefficent + "x^" + exponent; // if exponent is
    }
    else
    {
        return coefficent + "";
    }
}


public boolean equals(Object anObject)
{
    //equals method which trys to check if the object to be added
    if (anObject == null || getClass() != anObject.getClass())
    {
        return false;
    }
    Term otherTerm = (Term) anObject ;
    return (this.coefficent == otherTerm.getCoefficent()) &&
            this.exponent == otherTerm.getExponent();
}

public int compareTo(Term object)
{
    // what is the purpose and why does it work \\
    //  because the compare just to compare to object
    //  exp - object.exp give you a +, -, or 0
    return (this.exponent - object.exponent);
}}

KWLinkedList Класс:

public class KWLinkedList<E> extends AbstractSequentialList<E> {

/************************ Instance variables ****************************/
private Node<E> head = null ;               // Reference to head of the list
private Node<E> tail = null ;               // Reference to tail end of the list
private int size = 0;                       // Number of nodes in the list

/**************************** Methods *******************************/

// Add an item at the specified index.
@Override
public void add(int index, E obj) {
    listIterator(index).add(obj);
}

// Get the element at position index.
@Override
public E get(int index)
{
    return listIterator(index).next();
}

// Return the size of the list
@Override
public int size() {
    return size;
}

public ListIterator<E> listIterator(int index) // added method
{
    return new KWListIter(index) ; // returns the new list

}

/********************************** Inner Classes*******************************/
// A Node is the building block for a double-linked list.
private static class Node<E> {

    private E data;                   // data value in the node
    private Node<E> next = null;      // line to next node in the list
    private Node<E> prev = null;      // link to previous node in the list

    /**
     * Construct a node with the given data value.
     * @param dataItem The data value
     */
    private Node(E dataItem) {
        data = dataItem;
    }
} //end class Node

/** Inner class to implement the ListIterator interface. */
private class KWListIter implements ListIterator<E> {

    // Instance variables
    private Node<E> nextItem ;                  // Reference to next item in the iterator
    private Node<E> lastItemReturned;           // Reference to the last item returned by iterator
    private int index = 0;                      // Index of the current item

    /**
     * Construct a KWListIter that will reference the ith item.
     * @param i The index of the item to be referenced
     */
    public KWListIter(int i) {
        // Validate i parameter.
        if (i < 0 || i > size) {
            throw new IndexOutOfBoundsException(
                    "Invalid index " + i);
        }
        lastItemReturned = null; // No item returned yet.
        // Special case of last item.
        if (i == size) {
            index = size;
            nextItem = null;
        } else { // Start at the beginning
            nextItem = head;
            for (index = 0; index < i; index++) {
                nextItem = nextItem.next;
            }
        }
    }

    public void  set(E object) // added method
    {
        // takes the object passed in and makes sure its not null and last item returned
            if(object != null && lastItemReturned != null)
            {
                   lastItemReturned.data = object;
                   // sets the lastitemreturned data to the object
            }
            else
                {
                    // throws exception
                throw new IllegalStateException();
            }
    }

    public int indexOf(Object anObject)
    {
        int indexOf = 0;
        Node<E> currentIndex = head;

        while (currentIndex != null)
        {
            if (currentIndex.equals(anObject)) // checks at run time
            {
                return indexOf; // returns the index
            }
            indexOf++; // increments the index
            currentIndex = currentIndex.next; // points to the next node
        }

        return -1; // returns -1 if it couldnt find the index requested
    }

    public int lastIndexOf(Object anObject)
    {
        int indexOf = 0;
        int last = -1;
        Node<E> currentIndex = head;
        while (currentIndex != null)
        {
            if (currentIndex.equals(anObject)) // checks at run time
            {
                 last = indexOf; // sets the last int to the index found
            }
            indexOf++; // increments the index
            currentIndex = currentIndex.next; // points to the next node

        }

         return last; // returns the last occurrence of int
    }

    public void addFirst(E object)
    {
        if(head == null) // if head is null, then adds it to the beginning since its empty
        {
            head = new Node<E>(object);
        }
        else
        {
            // set the object to a temp
            // node then set the  temps next to head and then head to the temp
            Node <E> temp = new Node<E>(object);
            temp.next = head;
            head = temp;
        }

    }

    public void addLast(E object)
    {
        if(tail == null) // if tail null then just add the object to the end/beginning since its empty
        {
            tail = new Node<E>(object);
        }
        else
        {
            // set the object to a temp node then set the tails next to temp and then tail to the temp
            Node <E> temp = new Node<E>(object);
            tail.next = temp;
            tail = temp;
        }
    }
    public E getFirst()
    {
        if(head == null) // does this if head is 'empty'/null
        {
            throw new NoSuchElementException();
        }

        return head.data; // returns the element contained in head
    }
    public E getLast()
    {
        if(tail == null) // does this if tail is 'empty'/null
        {
            throw new NoSuchElementException();
        }

        return tail.data; // returns the element contained in tail
    }
    public Iterator<E> iterator()
    {
        return new  KWListIter(0) ; // returns a new iterator
    }
    public void remove() // added method
    {
        // makes sure lastitemreturned is not null
        if(lastItemReturned != null)
        {
            // removes the last item from this list and then sets it to null
            KWLinkedList.this.remove(lastItemReturned);
            lastItemReturned = null;

        }
        else
        {
            // throws exception
            throw new IllegalStateException();
        }
    }
    /**
     * Construct a KWListIter that is a copy of another KWListIter
     * @param other The other KWListIter
     */
    public KWListIter(KWListIter other) {
        KWListIter itr = new KWListIter(0);
        itr.index = other.index;
        itr.lastItemReturned = other.lastItemReturned;
        itr.nextItem = other.nextItem;
    }

    /**
     * Indicate whether movement forward is defined.
     * @return true if call to next will not throw an exception
     */
    @Override
    public boolean hasNext() {
        return nextItem != null;
    }

    /** Move the iterator forward and return the next item.
    @return The next item in the list
    @throws NoSuchElementException if there is no such object
     */
    @Override
    public E next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        lastItemReturned = nextItem;
        nextItem = nextItem.next;
        index++;
        return lastItemReturned.data;
    }

    /**
     * Indicate whether movement backward is defined.
     * @return true if call to previous will not throw an exception
     */
    @Override
    public boolean hasPrevious() {
        return (nextItem == null && size != 0)
                || nextItem.prev != null;
    }

    /**
     * Return the index of the next item to be returned by next
     * @return the index of the next item to be returned by next
     */
    @Override
    public int nextIndex() {
        return index;
    }

    /**
     * Return the index of the next item to be returned by previous
     * @return the index of the next item to be returned by previous
     */
    @Override
    public int previousIndex() {
        return index - 1;
    }

    /**
     * Move the iterator backward and return the previous item.
     * @return The previous item in the list
     * @throws NoSuchElementException if there is no such object
     */
    @Override
    public E previous() {
        if (!hasPrevious()) {
            throw new NoSuchElementException();
        }
        if (nextItem == null) { // Iterator past the last element
            nextItem = tail;
        } else {
            nextItem = nextItem.prev;
        }
        lastItemReturned = nextItem;
        index--;
        return lastItemReturned.data;
    }

    /**
     * Add a new item between the item that will be returned
     * by next and the item that will be returned by previous.
     * If previous is called after add, the element added is
     * returned.
     * @param obj The item to be inserted
     */
    @Override
    public void add(E obj) {
        if (head == null) { // Add to an empty list.
            head = new Node<E>(obj);
            tail = head;
        } else if (nextItem == head) { // Insert at head.
            // Create a new node.
            Node<E> newNode = new Node<E>(obj);
            // Link it to the nextItem.
            newNode.next = nextItem; // Step 1
            // Link nextItem to the new node.
            nextItem.prev = newNode; // Step 2
            // The new node is now the head.
            head = newNode; // Step 3
        } else if (nextItem == null) { // Insert at tail.
            // Create a new node.
            Node<E> newNode = new Node<E>(obj);
            // Link the tail to the new node.
            tail.next = newNode; // Step 1
            // Link the new node to the tail.
            newNode.prev = tail; // Step 2
            // The new node is the new tail.
            tail = newNode; // Step 3
        } else { // Insert into the middle.
            // Create a new node.
            Node<E> newNode = new Node<E>(obj);
            // Link it to nextItem.prev.
            newNode.prev = nextItem.prev; // Step 1
            nextItem.prev.next = newNode; // Step 2
            // Link it to the nextItem.
            newNode.next = nextItem; // Step 3
            nextItem.prev = newNode; // Step 4
        }
        // Increase size and index and set lastItemReturned.
        size++;
        index++;
        lastItemReturned = null;
    } // End of method add.

} //end class KWListIter} // end of KWLinkedList class

Мои проблемы Когда я запускаю свойОсновной метод, я в конечном итоге в бесконечный цикл, я верю, что это как-то связано с моими случаями цикла whileЭто была общая головная боль, работавшая над этим, и я начал просто добавлять туда случайные попытки, чтобы помочь поймать исключения, чтобы увидеть, что он печатает.Мне нужно было отдохнуть от этого, это было последнее средство.

Если вы можете указать на очевидное, это было бы хорошо.Спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...