Reputation: 633
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.
Upvotes: 0
Views: 590
Reputation: 3294
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.
Upvotes: 1
Reputation: 310990
Pointer l is not changed in your function. You change pointer lAux but l keeps its original value.
Upvotes: 1
Reputation: 42083
void DeleteFromPos(List &l, unsigned int p)
I believe you pass a pointer to node
by reference so that if the head of your list is to be deleted, you can update the pointer itself so that this change is visible to the caller. Yet you do:
List lAux = l;
which throws this potential away. In case p
equals 1
, you should do:
if (p == 1) {
List del = l;
l = l->next; // <-- updates pointer that was passed by reference
delete del;
}
Upvotes: 1