insecure trash
insecure trash

Reputation: 1

optimized code for deleting a node in singly linked list

can this piece of code be used to delete a node at a specified position

void del(node *&head,int position)
{
        int jump=0;
        node *temp=head;
        while(jump<position-1)
        {
            temp=temp->next;
            jump++;
        }
        node *copy=temp->next;
        temp->next=temp->next->next;
        delete copy;

also what is the most efficient method to delete a node in a specific position?

Upvotes: 0

Views: 283

Answers (1)

eerorika
eerorika

Reputation: 238311

can this piece of code be used to delete a node at a specified position

This is the correct algorithm for the most part. It doesn't handle deletion of position 0 correctly through so it cannot be used as such.

what is the most efficient method to delete a node in a specific position?

More efficient than this is to pass pointer to previous node as argument instead of pointer to head and position. But for given inputs, the algorithm that you've used is asymptotically optimal.

Upvotes: 1

Related Questions