首页 > 解决方案 > LinkedList Implementation Java - get(int index) - Explain what this code does

问题描述

The source code in java for getting an element from a linked list using an index

public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}

and the code for node()

Node<E> node(int index) {
    // assert isElementIndex(index);

    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

I can't understand why bitshift operator is used in the if condition. Can someone please explain?

标签: javalinked-list

解决方案


The term size >> 1 is equivalent to using size / 2. That is, the if condition will execute should the index be on the left side of the list. Otherwise, the else condition will be used.

The logic here is a simple divide and conquer approach: It guarantees that the code will only have to walk at most size / 2 items for a list with size number of items. Depending on the index, the search will either start at the end of the list or the beginning of the list.


推荐阅读