Why does linked list delete and insert operation have complexity of O(1) ? shouldn't it be of O(n)

后端 未结 5 1980
情歌与酒
情歌与酒 2021-02-04 03:00

It is said that the complexity of the LinkedList remove and the add operation is of O(1). and in case of ArrayList it is of O(n).

5条回答
  •  我在风中等你
    2021-02-04 03:32

    Yes, you are corrrect if you consider two operations (indexing and inserting) in one go. It is not true in this case because when you are inserting a node in the middle of a linked list, the assumption taken is that you are already at the address where you have to insert the node.

    The time complexity of accessing the node is O(n) whereas only inserting a node is O(1).

    Insertion at the head requires you to add the element and update the head pointer.

    newnode->next = head;
    head = newnode;
    

    Insertion at the tail requires you to keep a pointer to the tail element, add the element at the tail and update the tail pointer.

    tail->next = newnode;
    tail = newnode;
    

    Deleting the head element requires updating the head and deleting the previously head element.

    temp = head;
    head = head->next;
    delete temp; /* or free(temp); */
    

    All the above are trivial operations and don’t depend upon the number of elements in linked list. Hence, they are O(1)

    Deleting the tail element would, however, be a O(n) operation because even though you might have a tail pointer, you would still need the penultimate node that would be setup as the new tail node ( by updating the tail pointer and setting the node’s next member to NULL). For this, you need to traverse through the whole linked list.

    penultimate_el = find_penultimate_el(head); /* this is O(n) operation */
    delete tail; /* or free(tail) */
    tail = penultimate_el;
    tail->next = NULL;
    

提交回复
热议问题