There is a problem that I found myself stuck in. How do I duplicate even numbers as 2’s in a simply linked list? I tried to answer this question through AI but it didn’t give me the output I desired. Is there anyone that could show me how to solve this problem? That would be much appreciated thank you.
This is the code that the AI generated. What is the problem with the duplicateEven function? and what’s the solution?
#include <iostream>
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
void duplicateEvens(Node* head) {
Node* current = head;
while (current != nullptr) {
if (current->data % 2 == 0) {
Node* duplicate = new Node(2);
duplicate->next = current->next;
current->next = duplicate;
current = duplicate;
}
current = current->next;
}
}
void printList(Node* head) {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head->next->next->next->next->next = new Node(6);
std::cout << "Original list: ";
printList(head);
duplicateEvens(head);
std::cout << "List after duplicating evens: ";
printList(head);
// Clean up memory
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}
return 0;
}
New contributor
Sylas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.