P
P
Programist189462022-03-17 00:36:35
C++ / C#
Programist18946, 2022-03-17 00:36:35

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

2 answer(s)
W
Wataru, 2022-03-17
@wataru

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.

C
CityCat4, 2022-03-17
@CityCat4

Brutal? Calculate the size of the memory area occupied by the list, allocate one more of the same piece and copy it there via memmove (), then address to the new address.
But it won't work for you, you have a training example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question