Search code examples
c++algorithmfunctionlinked-listsingly-linked-list

Delete elements from a simple linked list starting at given position


I have implemented this function in this way:

typedef node* List;
void DeleteFromPos(List &l, unsigned int p) {
    List lAux = l;
    unsigned int count = 1;

    while (lAux) {      
        if (p == 1) {
            while (l) {
                List del = lAux;
                lAux = lAux->next;
                delete del;
                del = NULL;
            }
            lAux = NULL;
        } else if (count < p-1) {
                lAux = lAux->next;
                count++;
        } else {
            List del = lAux->next;
            if (del) {
                lAux->next = del->next;
                delete del;
                del = NULL;
            } else
                lAux = NULL;
        }
    }
}

The problem is when p==1, in this especial case all the elements are deleted but it looks like the l pointer still exist at the end. I need some advice about this.

EDIT: with some sugerence, the p ==1 case have his own loop, its ugly but it works.


Solution

  • Simplify your task by modularising. First have a function that deletes all elements in a list.

    deleteList(List *&head) {
       while (head) {
          List *l = head->next;
          delete head;
          head = l;
       }
    }
    

    Note *& - reference to a pointer. Thus the function modifies head parameter.

    Then have a function that locates n-th element. When you have n-th node call the above function.

    If you really need to do the job in a single function then do something like:

    deleteFromPosition(List *&head, unsigned int pos) {
      loop one: iterate through the list until n-th node is reached;
      loop two: iterate through the list tail deleting nodes as in the function above;
    }
    

    I am leaving details out for your exercise.