简体   繁体   English

LinkedList 获取方法

[英]LinkedList Get method

I have a get method for my singly linked list and they work fine but my instructor told me that he wants me to cut down on the code because I have too many special cases.我有一个单链表的 get 方法,它们工作正常,但我的导师告诉我他希望我减少代码,因为我有太多的特殊情况。 Problem being is that when I try to cut out some parts of my code, the code no longer works as it's supposed to.问题是,当我尝试删除代码的某些部分时,代码不再按预期工作。

The code written from me:我写的代码:

public E get(int index) {
    Node<E> f = first;

    // If index is bigger / smaller than Linked List size throw IndexOutOfBounds
    if (index > size || index < 0){
        throw new IndexOutOfBoundsException();
    }


    // Index Less than size and is not the first or last node.
    if (index < size && index > 0) {
        for (int i = 0; i < index; i++) {
            f = f.next;
        }
        return f.getValue();
    }

    // If the Linked List is empty + Index = 0 return null
    if (first == null && index == 0) {
        return null;
    }

    // If Linked List is not empty and index = 0 return first value
    if (index == 0) {
        return first.getValue();
    }

    // If index = end of list
    if (index == size) {
        return last.getValue();
    }


    // Return null if not found.
    return null;

}

So he tells me that I'm putting too much thought into it and there are only two cases needed, if the index is valid or not valid;所以他告诉我,我想太多了,只需要两种情况,如果索引有效或无效; which I agree with him on, so I try to shorten my code to this:我同意他的看法,因此我尝试将代码缩短为:

Node<E> f = first;

// If index is bigger / smaller than Linked List size throw IndexOutOfBounds
if (index > size || index < 0){
    throw new IndexOutOfBoundsException();
}


// Index Less than size and is not the first or last node.
if (index <= size && index >= 0) {
    for (int i = 0; i < index; i++) {
        f = f.next;
    }
}
return f.getValue();

and for my test cases I'm using a Linked List with these values:对于我的测试用例,我使用具有以下值的链表:

[Frank, George, Josh, Jim, Marry, Susie, John, Jim, Dakota, Levi, Jackson, Jeff, Walt, Matt] [弗兰克、乔治、乔什、吉姆、玛丽、苏西、约翰、吉姆、达科他、利维、杰克逊、杰夫、沃尔特、马特]

and my test cases are as follows in my test class:我的测试用例在我的测试类中如下:

System.out.println("Get Method Test ----------------------------");
System.out.println("First Index: " + ll.get(0));
System.out.println("Last Index: " + ll.get(ll.size()));
System.out.println("'Middle' Index: " + ll.get(5));
System.out.println("Empty list with index of 0: " + llempty.get(0));

Which throws a NullPointerException at the second test case of trying to get the last index:在尝试获取最后一个索引的第二个测试用例中抛出NullPointerException

Output:输出:

First Index: Frank
Exception in thread "main" java.lang.NullPointerException

I need to be able to demonstrate the following:我需要能够证明以下几点:

Test cases: index of zero, index at end of list, index in “middle” of list, empty list with index 0, index too big, index too small测试用例:索引为零,列表末尾的索引,列表“中间”的索引,索引为0的空列表,索引太大,索引太小

So I'm stuck here guys / gals, any help would be appreciated!所以我被困在这里伙计们/女孩们,任何帮助将不胜感激!

I would just make your code even more simple (the second if around your loop isn't needed):我只会让你的代码更简单(第二个if不需要你的循环):

//assume 0 based index
int current = 0;

//loop until we hit the requested index
while (current != index) {
 f = f.next;
 current++;
}

//return the right node
return f;

Assuming your initial check for index out of bounds is correct, this should never give you an issue.假设您对索引越界的初始检查是正确的,这永远不会给您带来问题。 However, if your indexes are 0 based, you need to change your out of bounds check to:但是,如果您的索引是基于 0 的,则需要将越界检查更改为:

if (index > size - 1 || index < 0) {

For example if there are 2 elements, you have indexes 0 and 1. An index of 2 is invalid in this case.例如,如果有 2 个元素,则索引为 0 和 1。在这种情况下,索引 2 无效。

There are two instances of the same mistake in your code.您的代码中有两个相同错误的实例。 You have to understand that index is zero-relative, which means that the last element in a list of size n would have the index n-1 .您必须了解索引是零相关的,这意味着大小为n的列表中的最后一个元素将具有索引n-1 The first mistake is in your new get() method:第一个错误是在你的新get()方法中:

// If index is bigger / smaller than Linked List size throw IndexOutOfBounds
if (index > size || index < 0){
    throw new IndexOutOfBoundsException();
}

Here you should check index >= size , as follows:在这里您应该检查index >= size ,如下所示:

// If index is bigger / smaller than Linked List size throw IndexOutOfBounds
if (index >= size || index < 0){
    throw new IndexOutOfBoundsException();
}

The second mistake is in your test code.第二个错误是在您的测试代码中。 Where you write你写的地方

System.out.println("Last Index: " + ll.get(ll.size()));

You should use ll.size() - 1 as follows:您应该使用ll.size() - 1如下:

System.out.println("Last Index: " + ll.get(ll.size() - 1));

Both of these things have been observed by others.这两件事都被其他人观察到了。 It is, however, necessary to fix them both.但是,有必要同时修复它们。

When I made those changes and ran your test it got to the last line and threw IndexOutOfBoundsException as expected.当我进行这些更改并运行您的测试时,它到达最后一行并按预期抛出IndexOutOfBoundsException I also tested "Index Too Small" and "Index Too Big" and got IndexOutOfBoundsException .我还测试了“索引太小”和“索引太大”并得到了IndexOutOfBoundsException

这可能不是唯一的原因(您只向我们展示了部分代码),但您弄乱了“大小”值,因为如果索引从 0 开始(像往常一样),最后一个元素应该在

index == size -1

Should have been本来应该

if (index >= size || index < 0){
        throw new IndexOutOfBoundsException();
    }

if (index < size && index >= 0) {
    for (int i = 0; i < index; i++) {
        f = f.next;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM