Question
I have a delete alternate function that deletes every other number in the linked list. like so: input {2, 4, 2, 4, 5, 6, 7};
I have a delete alternate function that deletes every other number in the linked list. like so:
input {2, 4, 2, 4, 5, 6, 7};
output: 2, 2, 5, 7
how can I modify the function so that it deletes every other number starting from the head? Like:
input {2, 4, 2, 4, 5, 6, 7};
output: 4, 4, 6
#include
typedef struct node { int data; struct node *next; } node;
node *create_node(int data) { node *new_node = malloc(sizeof(node)); if (new_node == NULL) { fprintf(stderr, "Error: Out of memory in create_node() "); exit(1); } new_node->data = data; new_node->next = NULL; return new_node; }
node *tail_insert(node *head, int data) { node *temp = head; if (head == NULL) return create_node(data); while (head->next != NULL) head = head->next; //for (temp = head; temp->next != NULL; temp = temp->next); // temp->next = create_node(data); // return head; //temp = head; //while (temp->next != NULL) // temp = temp->next; head->next = create_node(data); return temp; }
void print_list(node *head) { if (head == NULL) { printf("(empty list) "); return; } while (head != NULL) { printf("%d%c", head->data, (head->next == NULL) ? ' ' : ' '); head = head->next; } // for (temp = head; temp != NULL; temp = temp->next) // printf("%d%c", temp->data, (temp->next == NULL) ? ' ' : ' '); }
node *delete_alternative(node *head) { node *current = head; node *temp = current->next; if (head == NULL) return NULL; while(current != NULL && temp != NULL) { current->next = temp->next; free(temp); current = current->next; if (current != NULL) temp = current->next; } return head; }
int main(void) { int i; node *head = NULL; int a[] = {2, 4, 2, 4, 5, 6, 7}; for (i = 0; i < 7; i++) { head = tail_insert(head, a[i]); } print_list(head); head = delete_alternative(head); print_list(head); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started