Lets say, I have singly linkedlist with 5 elements in it. How will I resize the list if I delete an element with this specific situation -
My singly linkedlist is defined as 0->1->2->3->4
, where these numbers are the index of the list. Suppose I have function, f()
which return a pointer directly at index 2. From here, I want to delete 2 but don't know how to connect 1 to 3. How can I do that?
CodePudding user response:
For the case of a "singley-linked" list you will need to maintain the data-structure of for the "next" item in the list.
If in your case (it seems as though you are) constricted to use a function that returns a pointer to this link, then you can loop through and delete accordingly.
For example:
struct link *f(struct link *head) {
// Do work...
// is found struct link *target
return target;
}
struct link *delete_link(struct link *head, struct link *target) {
if (head == target) {
struct link *tmp = head;
struct link *new_head = tmp->next;
return new_head;
}
struct link *curr = head;
while (curr->next != target) {
struct link *tmp = curr;
curr = curr->next;
}
curr->next = target->next
free(target);
return head;
}
int main(int argc, char *argv[])
{
struct link {
// data
struct link *next;
};
// Construct list....
struct link *head = construct_list(1, 2, 3, 4);
// Do stuff...
struct link *target = f(list);
// Found a deletion target...
head = delete_link(target);
return 0;
}