I have a List class:
class List //Класс Список { private: data *Head; //Указатель на последний активный элемент или просто голова списка public: List(); ~List(); void Add(int x); void Show(); void addAfter(int x, int pos); }; data is my structure:
struct data { long int x; data *Next; }; I use the object of my class as a list. The functions Add (add) and output (Show) work, trying to bring to mind a function that will add an element at the specified position
It turned out this:
void List::addAfter(int x, int pos) { data *temp = new data; int number = 0; if(temp == NULL) { cout<<"List is empty"<<endl; return; } else { data *beg = temp; //запоминаем текущее состояние списка do //считаем сколько у нас в списке всего элементов { ++number; temp = temp->Next; }while(temp != NULL); if(pos > number) //если указанный номер позиции превышает кол-во элементов в списке { cout<<"Invalid position"<<endl; return; } temp = beg; //откатываем список в исходное состояние for(int i = 0; i < number; i++) { if(pos == i) { data *n_temp = new data; n_temp->x = x; n_temp->Next = temp->Next; temp->Next = n_temp; } else temp = temp->Next; } } } Well, actually, the function does not work, and I would like to do the opposite.
I'm confused in this thread, do not tell me what is wrong with me and what should I change?
data *temp = new data;- a mistake here. - Athari