Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way I can make this easily run in constant time instead of linear time?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Change

Node<E> cur = header;
while(cur.next != trailer) {
    cur = cur.next;
}

to

Node<E> cur = trailer.prev;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading