programmme to print data of linkedlist
Thu Oct 17 2024 12:41:47 GMT+0000 (Coordinated Universal Time)
Saved by
@E23CSEU1151
#include <iostream>
using namespace std;
struct node {
int data;
struct node* next;
};
void print_data(struct node* head) {
if (head == NULL) {
cout << "Linked list is empty." << endl;
return; // Return early if the list is empty
}
struct node* ptr = head; // Initialize the pointer to head
while (ptr != NULL) {
cout << ptr->data << " ";
ptr = ptr->next; // Move to the next node
}
cout << endl; // Print a newline at the end
}
int main() {
// Create the head node
node* head = new node;
head->data = 10;
head->next = NULL;
// cout << "1st node is " << head->data << endl;
// Create the second node
node* second = new node;
second->data = 45;
second->next = NULL;
head->next = second;
// cout << "2nd node is " << second->data << endl;
// Create the third node
node* third = new node;
third->data = 30;
third->next = NULL;
head->next->next = third; // Link second to third
// cout << "3rd node is " << third->data << endl;
// Print the linked list
cout << "Linked list: ";
print_data(head);
// Clean up allocated memory
delete third; // Delete in reverse order
delete second;
delete head;
return 0;
}
content_copyCOPY
Comments