Question

C PROGRAMMING Create two void functions that 1) delete a specific value in a linked list...

C PROGRAMMING

Create two void functions that 1) delete a specific value in a linked list and 2) delete all instances of that value. Both functions' only parameter is the number that will be erased.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the code below.

CODE

/* Given a reference (pointer to pointer) to the head of a list

and a key, deletes the first occurrence of key in linked list */

void deleteNode(int key)

{

// Store head node

struct Node* temp = *head_ref, *prev;

// If head node itself holds the key to be deleted

if (temp != NULL && temp->data == key)

{

*head_ref = temp->next; // Changed head

free(temp); // free old head

return;

}

// Search for the key to be deleted, keep track of the

// previous node as we need to change 'prev->next'

while (temp != NULL && temp->data != key)

{

prev = temp;

temp = temp->next;

}

// If key was not present in linked list

if (temp == NULL) return;

// Unlink the node from linked list

prev->next = temp->next;

free(temp); // Free memory

}

/* Given a reference (pointer to pointer) to the head of a list and

a key, deletes all occurrence of the given key in linked list */

void deleteKey(int key)

{

// Store head node

struct Node* temp = *head_ref, *prev;

// If head node itself holds the key or multiple occurrences of key

while (temp != NULL && temp->data == key)

{

*head_ref = temp->next; // Changed head

free(temp); // free old head

temp = *head_ref; // Change Temp

}

// Delete occurrences other than head

while (temp != NULL)

{

// Search for the key to be deleted, keep track of the

// previous node as we need to change 'prev->next'

while (temp != NULL && temp->data != key)

{

prev = temp;

temp = temp->next;

}

// If key was not present in linked list

if (temp == NULL) return;

// Unlink the node from linked list

prev->next = temp->next;

free(temp); // Free memory

//Update Temp for next iteration of outer loop

temp = prev->next;

}

}

NOTE:

I have provided the code assuming that the linked list node is represented as:

// A linked list node

struct Node

{

    int data;

    struct Node *next;

};

struct Node* head; // points to the head of the linked list

Add a comment
Know the answer?
Add Answer to:
C PROGRAMMING Create two void functions that 1) delete a specific value in a linked list...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT