#include <iostream> using namespace std; struct Node { int key; Node* next; }; Node* add_to_list(Node *end, int first, int last){ for (int i=first; i<=last; i++){ Node *tmp = new Node(); tmp->key = i; tmp->next = nullptr; end->next = tmp; end = tmp; } return end; } void print_available(Node *start){ cout << "Available keys: " << start->key; while (start = start->next){ cout << ", " << start->key; } cout << endl; } Node* delete_by_key(Node *start, int key){ if (start->key == key){ Node *tmp = start; start = start->next; delete tmp; return delete_by_key(start, key); } Node *cur = start; while (cur){ if (cur->next != nullptr && cur->next->key == key){ Node *tmp = cur->next; cur->next = cur->next->next; delete tmp; } cur = cur->next; } return start; } int main() { Node *start = new Node(); start->key = 1; start->next = nullptr; Node* end = add_to_list(start, 2, 5); end = add_to_list(end, 1, 5); cout << "Start" << endl; print_available(start); start = delete_by_key(start, 1); print_available(start); cout << "Middle" << endl; print_available(start); start = delete_by_key(start, 3); print_available(start); cout << "End" << endl; print_available(start); start = delete_by_key(start, 5); print_available(start); return 0; }
Standard input is empty
Start Available keys: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 Available keys: 2, 3, 4, 5, 2, 3, 4, 5 Middle Available keys: 2, 3, 4, 5, 2, 3, 4, 5 Available keys: 2, 4, 5, 2, 4, 5 End Available keys: 2, 4, 5, 2, 4, 5 Available keys: 2, 4, 2, 4