897 views
1 votes
1 votes
There is a singly linked list. We have a pointer to a particular node(it is not tail node). what is the time and space complexity required to delete this node?

my approach is... As there is no previous pointer so we traverse the list from the starting to just before the concerned node. then we adjust the pointers like this

let ptr be a pointer pointing to the node to be deleted

while(temp->next!=ptr)
{

    temp=temp->next;     //temp will point to the node left to ptr

}

temp->next=ptr->next;

free(ptr);

 

if the node to be deleted is the second last node then we have to traverse the list upto 3rd element from the last node. so I'm getting time complexity as O(n) and space complexity O(1).
but in the book the time complexity is mentioned O(1)
where am I going wrong?

2 Answers

0 votes
0 votes
we can delete the element in O(1) time complexity by using the copying element method.

suppose, the elements in the linked list are 1->2->3->4. The node to be deleted is 3(denoted by X). let's take the temp pointer which points to the node just after the node is to be deleted(which means X points to node 3 and temp points to node 4). Now follow the below procedure:-

temp=X->next; (making temp to point node 4)

X->data=temp->data;

X->next=temp->next;

free(temp);

This procedure takes only O(1) time to delete any node except the last node.

finally, time complexity=O(1) and  space complexity=O(1)