对LinkedList源代码中entry函数的一点启示
看下entry的代码:
/** * Returns the indexed entry. */ private Entry<E> entry(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size); Entry<E> e = header; if (index < (size >> 1)) { for (int i = 0; i <= index; i++) e = e.next; } else { for (int i = size; i > index; i--) e = e.previous; } return e; }这里有个技巧非常用得非常的好,就是取数据的时候会判断当前的索引是在链表的前半部分还是后半部分,根据不同的位置来做遍历(前半部分的话从header往索引高的元素遍历,在后半部分从索引往下降得部分遍历)。太强悍了,如果自己当时去写这个算法的话估计还是用那种暴力遍历的方式。。。。