gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Write c++ function that print data contained in each node
- User
Write c++ function that print data contained in each node
- Assistant
Sure! Here's an example of a C++ function that prints the data contained in each node of a linked list:
#include <iostream> // Node structure struct Node { int data; Node* next; }; // Function to print data in each node void printList(Node* head) { Node* current = head; while (current != nullptr) { // Print data in current node std::cout << current->data << " "; // Move to next node current = current->next; } std::cout << std::endl; } // Test program int main() { // Create nodes Node* node1 = new Node{1, nullptr}; Node* node2 = new Node{2, nullptr}; Node* node3 = new Node{3, nullptr}; // Connect nodes node1->next = node2; node2->next = node3; // Print data in each node printList(node1); // Clean up memory delete node1; delete node2; delete node3; return 0; }In this example, we have a simple linked list with three nodes, each containing an integer data value. The
printListfunction takes the head node of a linked list as an argument and prints the data in each node by traversing the list. In themainfunction, we create the nodes, connect them, and then call to print the data in each node. Finally, we clean up the memory by deleting the nodes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.