Advertisements
I am new to java algorithms and doubly linked list. I have been playing around with them quite a lot trying to learn. What would be the best way to make this algorithm run in O(1) instead of O(n) (its a doubly linked list)? I appreciate any help.
public void add(E e) {
Node<E> cur = header;
while(cur.next != trailer) {
cur = cur.next;
}
Node<E> newNode = new Node<E>(e, cur, cur.next);
cur.next = newNode;
trailer.prev = newNode;
size++;
}
>Solution :
Change
Node<E> cur = header;
while(cur.next != trailer) {
cur = cur.next;
}
to
Node<E> cur = trailer.prev;