Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Complexity in singly link list

I am studying data-structure: singly link list.

The website says singly linked list has a insertion and deletion time complexity of O(1). Am I missing something?

website link

enter image description here

I do this in C++, and I only have a root pointer. If I want to insert at the end, then I have to travel all the way to the back, which means O(n).

like image 367
Anni_housie Avatar asked Nov 05 '16 20:11

Anni_housie


People also ask

What is the time complexity for inserting at the end of linked list?

The time complexity for the Inserting at the end depends if you have the location of the last node, if you do, it would be O(1) other wise you will have to search through the linked list and the time complexity would jump to O(n).

What is the time complexity of insert a node at the end in a singly linked list there are n nodes in a singly linked list?

Answer: A) Explanation: We need to traverse to the end of the LinkedList and set it next to the new element. So, the traversal will take O(n) time complexity.


2 Answers

The explanation for this is, that the big O notation in the linked table refers to the function implementation itself, not including the list traversal to find the previous reference node in the list.

If you follow the link to the wikipedia article of the Singly-LinkedList implementation it becomes more clear:

function insertAfter(Node node, Node newNode)
function removeAfter(Node node)     

The above function signatures already take the predecessor node as argument (same for the other variants implicitly).

Finding the predecessor is a different operation and may be O(n) or other time complexity.

like image 127
πάντα ῥεῖ Avatar answered Oct 04 '22 06:10

πάντα ῥεῖ


You missed the interface at two places:

  1. std::list::insert()/std:list::erase() need an iterator to the element where to insert or erase. This means you have no search but only alter two pointers in elements in the list, which is constant complexity.

  2. Inserting at the end of a list can be done via push_back. The standard requires this to be also O(1). Which means, if you have a std::list, it will store first and last element.

EDIT: Sorry, you meet std::forward_list. Point 1 holds also for this even if the names are insert_after and erase_after. Points 2 not, you have to iterate to the end of the list.

like image 22
user6556709 Avatar answered Oct 04 '22 07:10

user6556709