You have already provided the solution in your question. Function
DeleteNode (struct node* head, int pos)
does already most of what you want to do. It deletes the node with (1-based) index
pos
from the list passed as argument
head
. All you have to do is loop over your second list that contains the indices which are to be deleted and call DeleteNode for every element in your second list. So you end up with code like:
struct node* p;
for (p = list2Head; p != NULL; p = p->next)
DeleteNode (list1Head, p->value);
But before you go for it, I want to put in a brief discussion of your function
DeleteNode
.
(1) I would suggest to define pos as a zero-based index; just because that's what most C programmers are used to. (Don't forget to modify your second list accordingly.)
(2) At the start of the function you call LinkedListLength to get the number of elements in that list. This will probably require a full loop over all elements in the list, eating up many unnecessary CPU cylces. And it can easily be avoided as you are going to iterate over the list anyhow. Here is the code after (1) and (2) have been incorporated:
struct node* DeleteNode (struct node* head, int idx)
{
struct node* temp = head;
int i;
if (head != NULL && idx == 0)
head = head->next;
else
{
for (i = 1; i < idx && temp->next; ++i)
temp = temp->next;
if (temp->next == NULL)
printf ("ERROR: Node does not exist!\n");
else
temp->next = temp->next->next;
}
return head;
}
(3) The DeleteNode function always returns the head-pointer of the list, which is not very useful. It probably should return the deleted element. It is very likely that the element has been dynamically allocated and hence must be returned to the heap after removal. By returning its pointer, the caller of the function has a chance to perform the necessary
free
. At the same time we can remove the printf statement, which is kind of nasty in a low level routine. Not all future users of your function may want your function to print anything to stdout. Now that we return the deleted element, the caller can detect the problem by looking at the returned node pointer. If it's NULL the function has failed.
struct node* DeleteNode (struct node* head, int idx)
{
struct node* delNode = NULL;
if (head == 0)
return NULL;
if (head != NULL && idx == 0)
{
delNode = head;
head = head->next;
}
else
{
struct node* p = head;
int i;
for (i = 1; i < idx && p->next; ++i)
p = p->next;
if (p->next == NULL)
return NULL;
delNode = p->next;
p->next = delNode->next;
}
return delNode;
}
I have not tested and debugged the code above, but just wanted to pass on a couple of ideas how to improve your code. I'd recommend single-stepping through the code with several test cases.
Hope that was helpful.