Given the following data structure:
typedef struct list{
int num1, num2, num3;
struct list * next;
} node;
I have this function to delink a node in case it meets a X condition and then link it to another linked list such that I have a linked list with all the delinked nodes.
void delinkNodes(node * register, node ** registerDeleted) {
node * auxNode;
while(register->next!= NULL && register->next->next!= NULL) {
if (helperCheckCondition(register->next)) {
printf("De-linking node!\n");
auxNode= register->next->next;
*registerDeleted= register->next;
register->next=auxNode;
}
else {
register=register->next;
}
}
}
It works since after call the function, if I try to traverse the new linked list it prints out the last delinked node.
The issue is that: It's only the last delinked node. I can't seem to think of a way of linking the delinked nodes together. Then there is the other issue of setting the last node->nextvalue to NULL.
Without writing code in an answer (for now..): What do I need to use in order to solve this in the best possible way? More aux variables...some pattern I might be forgetting...any hints?
CodePudding user response:
Some issues:
You need to distinguish between the first node to add to the result list and the next ones: only the first time do you need to assign to
*registerDeleted
, as that is the head node of that list, but the other times you need to extend that list, which does not impact the value of*registerDeleted
. So you need a helper variable that will point to the tail of that result list.The condition
register->next->next != NULL
suggests that the tail node could never be candidate for deletion. This is probably not what you intended.Don't forget to set the last
next
pointer in the result list toNULL
.
If you cannot figure it out, here is a hidden solution:
void delinkNodes(node * register, node ** registerDeleted) {
if (register == NULL) return;
node * currentNode = register->next;
node * tailNode = NULL;
while (currentNode != NULL) {
if (helperCheckCondition(currentNode)) {
printf("De-linking node!\n");
register->next = currentNode->next;
if (tailNode == NULL) { // First time only
tailNode = *registerDeleted = currentNode;
} else {
tailNode = tailNode->next = currentNode;
}
tailNode->next = NULL; // Make sure the end of the list is marked!
}
else {
register = currentNode;
}
currentNode = register->next;
}
}