#include <iostream> #include <conio.h> using namespace std; struct List { int a; List* next; }; void Print(List* c) { List* print = c; while (print) { cout << print->a << "->"; print = print->next; } cout << "NULL" << endl; } void Remove(List** begin) { List* t = new List; while (*begin != NULL) { t = *begin; *begin = t->next; } return; } void Add_end(List* end) { List* t = new List; t->a = NULL; t->next = NULL; cin >> t->a; end->next = t; return; } int main() { List* begin = new List; begin->a = NULL; begin->next = NULL; cout << "Input the length of the queue" << endl; int k; cin >> k; cout << "Input the queue" << endl; cin >> begin->a; List* end = begin; for (int i = 0; i < k - 1; i++) { end->next = new List; end = end->next; cin >> end->a; end->next = NULL; } Print(begin); int ind = 100; cout << "If you want to end the program enter '0'" << endl; while (ind != 0) { cout << "If you want to add element enter '1' and if you want to delete enter '2'" << endl; cin >> ind; if (ind == 1) { Add_end(end); Print(begin); } if (ind == 2) { Remove(&begin); Print(begin); } } _getch(); return 0; } 

I can not delete the first element, I suspect that I should use delete but not sure. Tell me how to modify the function Remove.

  • 2
    It would be interesting to listen to your version, what you generally do in the Remove function ... Just for your interest - how do you imagine what is going on in it ... - Harry
  • First look where you need to put delete - Simon Shelukhin
  • In the Remove function here, I assign the address of the next element to the beginning. I do not know how to do it right, so I ask for help, could you write how this function should look like ???? - toshka-pitoshka
  • So what does the loop do in your function Remove ? The loop performs repetitive actions. What action are you going to repeat ? - AnT
  • oh thank you, i got it, i'm so humiliating the whole list - toshka-pitoshka

1 answer 1

 #include <iostream> #include <conio.h> using namespace std; struct List { int a; List* next; List(int a = 0):a(a),next(nullptr){} }; void Print(List* c) { List* print = c; while (print) { cout << print->a << "->"; print = print->next; } cout << "NULL" << endl; } void Remove(List*&begin) { if (begin) { List * cur = begin->next; delete begin; begin = cur; } } void Add_end(List*&begin, int n) { if (begin == nullptr) { begin = new List(n); } else { List * cur = begin; for(; cur->next; cur = cur->next); cur->next = new List(n); } } int main() { List *begin = 0; cout << "Input the length of the queue" << endl; Print(begin); int ind = 100; cout << "If you want to end the program enter '0'" << endl; while (ind != 0) { cout << "If you want to add element enter '1' and if you want to delete enter '2'" << endl; cin >> ind; if (ind == 1) { cout << "Value to add: "; int n; cin >> n; Add_end(begin,n); Print(begin); } if (ind == 2) { Remove(begin); Print(begin); } } _getch(); return 0; }