Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, Actually i tried to code for the low time complexity in linked list deletion, but can't able to find out the logic for that. can u help me??

whole iteration logic i know but i need low complexity logic help me furthur...

What I have tried:

C++
#include<iostream>
using namespace std;

void Deletion(Mynode** p_node, int p_Val)
{
     if(*p_node == NULL)                    return ;

     Mynode* tmp = *p_node, prev = *p_node;
     while(tmp != NULL)
     {
          if(tmp->val == p_Val)
          {
              //some miss logic will be there, i need less iteration.
              prev->m_Next = tmp->m_Next;
              delete tmp;
              return ;
          }
          prev = tmp;
          tmp = tmp->m_Next;
     }
}
Posted
Updated 6-Dec-23 6:10am
v2

1 solution

At the beginning of the function you should make sure that p_node is not a nullptr before the pointer is used. Checking for nullptr at the beginning could avoid unexpected errors. There is still a problem in this source code if the first element is to be deleted. A correction would be necessary here.

Is there more information about the data? Are the elements sorted and can elements be contained more than once?

Only the first element found with the specified value is deleted here. If the value occurs more than once in the list and all occurrences are to be deleted, the loop would have to be continued after one occurrence is deleted.

Special knowledge about the distribution of the values could possibly lead to optimizations.

The time complexity of the Deletion function above depends on the number of elements in the linked list. If the list is run through to find the element to be deleted or all random occurrences of it, it is a linear search. Thus, it must be assumed that in the worst case, the entire list must be run through to find the element to be deleted or all random occurrences of it. Overall, the average and worst time complexity of the current implementation could be O(n).
 
Share this answer
 
v2
Comments
CPallini 7-Dec-23 2:12am    
5.
Andre Oosthuizen 7-Dec-23 13:56pm    
And mine +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900