If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Sure! Here's a C++ implementation to display (print) the elements of a singly linked list:
cppCopy code
#include <iostream> using namespace std; // Node structure for singly linked list struct Node { int data; Node* next; }; // Function to create a new node with the given data Node* createNode(int data) { Node* newNode = new Node(); newNode->data = data; newNode->next = nullptr; return newNode; } // Function to insert a new node at the end of the linked list void insertEnd(Node*& head, int data) { Node* newNode = createNode(data); if (head == nullptr) { head = newNode; return; } Node* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = newNode; } // Function to display the elements of the linked list void displayLinkedList(Node* head) { Node* temp = head; while (temp != nullptr) { cout << temp->data << " "; temp = temp->next; } cout << endl; } // Function to free memory allocated for the linked list void deleteLinkedList(Node*& head) { while (head != nullptr) { Node* temp = head; head = head->next; delete temp; } } int main() { Node* head = nullptr; // Inserting elements into the linked list insertEnd(head, 1); insertEnd(head, 2); insertEnd(head, 3); insertEnd(head, 4); insertEnd(head, 5); // Displaying the linked list cout << "Linked List: "; displayLinkedList(head); // Free memory and delete the linked list deleteLinkedList(head); return 0; }
In this code, we define a
Node
structure to represent each element in the linked list. ThecreateNode
function is used to create a new node with the given data. TheinsertEnd
function inserts a new node at the end of the linked list. ThedisplayLinkedList
function traverses the linked list from the head node to the tail node and prints the data values of each node. Finally, thedeleteLinkedList
function frees the memory allocated for the linked list to avoid memory leaks.When you run this code, it will display the elements of the linked list:
1 2 3 4 5
.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform