Question: Write a function that deletes the n th element from a linked list. If the linked list doesn't even have n nodes, don't delete any

Write a function that deletes the nth element from a linked list. If the linked list doesn't even have n nodes, don't delete any of them. The function signature is: node *deleteNth(node *head, int n). Try implementing the function iteratively and recursively. (In terms of how to interpret n, you can start counting your nodes from zero or one; your choice.)

Write a function that deletes every other element in a linked list. (Try writing it both ways: one where it starts deleting at the head of the list, and one where it starts deleting at the element just after the head of the list.) Can you write this both iteratively and recursively?

#include

#include

#include

typedef struct node

{

int data;

struct node *next;

} node;

node *create_node(int data)

{

node *ptr = malloc(sizeof(node));

if (ptr == NULL)

{

fprintf(stderr, "Error: Out of memory in create_node() ");

exit(1);

}

ptr->data = data;

ptr->next = NULL;

return ptr;

}

node *tail_insert(node *head, int data)

{

node *temp = head;

if (head == NULL)

return create_node(data);

for (temp = head; temp->next != NULL; temp = temp->next)

;

temp->next = create_node(data);

return head;

}

void print_list(node *head)

{

node *temp;

if (head == NULL)

{

printf("Empty list ");

return;

}

for (temp = head; temp != NULL; temp = temp->next)

printf("%d%c", temp->data, (temp->next == NULL) ? ' ' : ' ');

}

int main(void)

{

int i, r;

node *head = NULL;

srand((unsigned int)time(NULL));

for (i = 0; i < 5; i ++)

{

printf("Inserting...%d ", r = rand() % 20 +1);

head = tail_insert(head, r);

}

print_list(head);

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!