0

Hi I have written such a this code and I want to know that : its time complexity is O(n) ?

      DNode header = new DNode(null, null, null);
        DNode trailer = new DNode(null, header, null);
        header.next = trailer;
        for (Point point : pointList) {
            DNode node = new DNode(point, header, trailer);
            dList.addLast(node);
            header = node;
        }

I want to copying all objects from the pointList(ArrayList) to a dList(Doubly-Linked list). thanks

1 Answer 1

3

Yes. There's only one obvious loop here, which is O(n) - and everything within the loop is O(1), assuming a sensible implementation of the doubly-linked list.

Sign up to request clarification or add additional context in comments.

6 Comments

I have a problem that adding a list to the end of the doubly linked list in such a way has O(n) or O(1)?
@user472221: Well you haven't told us what implementation you're using, but generally speaking a doubly-linked list has O(1) time for insertion at either end. If you're using LinkedList<T> from the JDK, that's certainly true.
public void addLast(DNode v) { addBefore(trailer, v); }
@user472221: Well what does addBefore do?
public void addBefore(DNode v, DNode z) throws IllegalArgumentException { DNode u = v.getPrev();// may throw an IllegalArgumentException!! z.setPrev(u); z.setNext(v); u.setNext(z); v.setPrev(z); size++; }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.