Answer the question
In order to leave comments, you need to log in
How to copy a list in C (C)?
Hello, given a list with values, how to make a copy of it
Node* createList()//ввод списка с клавиатуры
{
Node* List; //создание вершины списка
List = NULL;
int N = 0;
int n = 0;
printf("Введите количество элементов: ");
scanf_s("%d", &N);
puts("Введите список");
for (int i = 0; i < N; i++)
{
printf("Элемент: ");
scanf_s("%d", &n);
List = add(List, n);
}
return List;
}
Node* add(Node* List, int n)//добавление элемента в список
{
if (List == NULL)//если список пуст,то создаем первый элемент
{
List = new Node; //выделяем память и заполняем поля
List->inf = n;
List->link = NULL;
}
else //иначе добавляем в конец
{
Node* last;
last = List;//переменная для хранения текущего узла, указатель на текущий узел
while (last->link)
{
last = last->link; //находим последний элемент
}
last->link = new Node; //выделяем память и заполняем поля
last->link->inf = n; //добавляем новый элемент
last->link->link = NULL;
}
return List;
}
Answer the question
In order to leave comments, you need to log in
Iterate through the list, adding elements to the end of the new list.
Just don't use your add function - it iterates over the entire list every time. Get a separate variable that will point to the end of the created list and add a new element to it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question