Созданный связанный список не возвращает правильный индекс - PullRequest
1 голос
/ 01 июля 2019

Я создал список, который идет {50, 10, 60, 30, 40} и хочу вернуть индекс, когда я достигну 30 в моем Связанном списке, однако моя программа всегда возвращает -1 (в основном она не может увеличивать иверните мой индекс).Я не уверен, как вернуть индекс в другом поместье, если я не могу привести объект anEntry к целому числу и сравнить его с моим индексом.

class MyLinkedList {
    private Node firstNode; // index = 0
    private int length;
    public MyLinkedList() {
        firstNode = null;
        length = 0;
    } // end default constructor
    /** Task: Adds a new entry to the end of the list.
     * @param newEntry the object to be added as a new entry
     * @return true if the addition is successful, or false if not */
    public boolean add(Object newEntry) {
        Node newNode = new Node(newEntry);
        if (isEmpty())
            firstNode = newNode;
        else {
            Node lastNode = getNode(length-1);
            lastNode.next = newNode;
        }
        length++;
        return true;
    } // end add
    /** Task: Adds a new entry at a specified index
     * @param newEntry the object to be added at the specified index
     * @return true if successful, or false if not */
    public boolean add(int index, Object newEntry) {
        boolean isSuccessful = true;
        if ((index >= 0) && (index <= length)) {
            Node newNode = new Node(newEntry);
            if (isEmpty() || (index == 0)) {
                newNode.next = firstNode;
                firstNode = newNode;
            }
            else {
                Node nodeBefore = getNode(index - 1);
                Node nodeAfter = nodeBefore.next;
                newNode.next = nodeAfter;
                nodeBefore.next = newNode;
            }
            length++;
        }
        else
            isSuccessful = false;
        return isSuccessful;
    } // end add
    /** Task: Determines whether the list contains a given entry.
     * @param anEntry the object that is the desired entry
     * @return true if the list contains anEntry, or false if not */
    public boolean contains(Object anEntry) {
        boolean found = false;
        Node currentNode = firstNode;
        while (!found && (currentNode != null)) {
            if (anEntry.equals(currentNode.data))
                found = true;
            else
                currentNode = currentNode.next;
        } // end while
        return found;
    } // end contains
    /** Task: Gets an entry in the list.
     * @param the desired index
     * @return the desired entry, or
     * null if either the list is empty or index is invalid */
    public Object getEntry(int index) {
        Object result = null; // result to return
        if (!isEmpty() && (index >= 0) && (index < length))
            result = getNode(index).data;
        return result;
    } // end getEntry
    /** Task: Gets index of an entry in the list.
     * @param the desired entry
     * @return index of the first occurrence of the specified entry
     * in this list, or -1 if this list does not contain the entry */
    public int getIndex(Object anEntry) {
        Node currentNode = firstNode;
        int index = 0; // result to return
        while (anEntry != currentNode.data) {
           currentNode = currentNode.next;
           index++;
           if (anEntry.equals(currentNode.data)){
               break;
           }
           else {
               return -1;
           }
        }
        return index;
    } // end getIndex
    private Node getNode(int index) {
        Node currentNode = firstNode;
        // traverse the list to locate the desired node
        for (int counter = 0; counter < index; counter++)
            currentNode = currentNode.next;
        return currentNode;
    } // end getNode
        private Node getNode(int index) {
        Node currentNode = firstNode;
        // traverse the list to locate the desired node
        for (int counter = 0; counter < index; counter++)
            currentNode = currentNode.next;
        return currentNode;
    } // end getNode
    private class Node {
        private Object data; // data portion
        private Node next; // link to next node

        private Node(Object dataPortion) {
            data = dataPortion;
            next = null;
        } // end constructor
        private Node(Object dataPortion, Node nextNode) {
            data = dataPortion;
            next = nextNode;
        } // end constructor
        private void setData(Object dataPortion) {
            data = dataPortion;
        } // end setData
        private Object getData() {
            return data;
        } // end getData
        private void setNextNode(Node nextNode) {
            next = nextNode;
        } // end setNextNode
        private Node getNextNode() {
            return next;
        } // end getNextNode
    } // end Node
} // end MyLinkedList

1 Ответ

1 голос
/ 01 июля 2019

Проблема в том, что ваш цикл while никогда не выполняет более одной итерации.

if (anEntry.equals(currentNode.data)){
    break;
}
else {
    return -1;
}

Если текущий элемент соответствует, то я нашел элемент, чтобы мы могли остановиться. Если это не так, то список не содержит этот элемент. Должно быть относительно ясно, что эта логика неверна. То, что текущий элемент не совпадает, не означает, что последующие элементы могут не совпадать.

Вы можете продемонстрировать это далее, заметив, что getIndex(50) на самом деле возвращает правильный индекс: ноль. Ваше утверждение " моя программа всегда возвращает -1 " на самом деле неверно.

Нам нужно поменять местами эту логику - вернуть -1 только после того, как мы уже попробовали все элементы.

while (anEntry != currentNode.data) {
    currentNode = currentNode.next;
    index++;
    if (anEntry.equals(currentNode.data)){
        return index;
    }
}
return -1;

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

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