В списке содержится несколько нулей. Разместить их вначале списка
Помогите написать реализацию чтобы нулевые элементы выводились в начале списка, не могу понять.
Ниже представлен код.
Заранее спасибо.
#include
using namespace std;
struct Node // Узел {
int value; // Значение узла (значение)
Node* next; // Следующий элемент узла
};
int main(int argc, char const* argv[]) { setlocale(LC_ALL, "Rus");
Node* head = NULL; // голова списка
Node* tail = NULL; // последний элемент списка
int currentValue; // текущее значение
Node* newNode = 0; // текущий узел
int N;
cout << "Введите кол-во чисел в списке: ";
cin >> N;
for (int i = 0; i < N; i++) {
cout << "Введите число: ";
cin >> currentValue;
newNode = new Node();
newNode->value = currentValue;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
Node* current = head; //Указатель на первый элемент списка (на голову)
cout << "\nСписок до изменений: \n";
while (current != NULL) {
cout << current->value << " ";
current = current->next;
}
cout << endl;
current = head;
Node* next = NULL; // Следующий элемент списка
Node* beginZero = NULL;
for (int i = 1; i <= N; i++)
next = current->next;
{
if (currentValue == 0) beginZero = current;
}
for (int i = 1; i <= N; i++)
next = current->next;
{
if (currentValue == !0) beginZero = current;
}
current = next;
current = head;
cout << "\nСписок после изменений: \n";
while (current != NULL) {
cout << current->value << " ";
current = current->next;
}
cout << endl;
return 0;
}
Ответы (1 шт):
Автор решения: alezhu
→ Ссылка
Или при вводе добавляете нули в начало списка сразу:
if (head == nullptr) {
head = newNode;
tail = newNode;
}
else if (currentValue == 0) {
newNode->next = head;
head = newNode;
}
else {
tail->next = newNode ;
tail = newNode;
}
Если нужно все таки после заполнения, то можно так:
cout << "\nСписок до изменений: \n";
while (current != nullptr) {
cout << current->value << " ";
current = current->next;
}
cout << endl;
current = head;
if(current != nullptr)
while (current->next != nullptr)
{
auto next = current->next;
if (next->value == 0) {
current->next = next->next;
next->next = head;
head = next;
} else {
current = next;
}
}
current = head;
cout << "\nСписок после изменений: \n";