#include <iostream> using namespace std; struct node { int data; struct node* next; }; void add_at_end(struct node *head , int data){ struct node *ptr, *temp; temp = new node; // Allocate new node temp->data = data; // Set data for the new node temp->next = NULL; // Initialize next pointer if (head == NULL) { head = temp; // If the list is empty return; } ptr = head; // Start from the head while (ptr->next != NULL) { ptr = ptr->next; } ptr->next = temp; // Link the last node to the new node } void print_data(struct node* head) { if (head == NULL) { cout << "Linked list is empty." << endl; return; } struct node* ptr = head; while (ptr != NULL) { cout << ptr->data << " "; ptr = ptr->next; } cout << endl; // Print a newline at the end } int main() { // Create the head node node* head = new node; head->data = 10; head->next = NULL; // Create the second node node* second = new node; second->data = 45; second->next = NULL; head->next = second; // Create the third node node* third = new node; third->data = 30; third->next = NULL; head->next->next = third; // Link second to third // Print the linked list before adding cout << "Linked list before adding: "; print_data(head); // Add a new node at the end add_at_end(head, 67); // Print the updated linked list cout << "Updated linked list after adding 67: "; print_data(head); // Clean up allocated memory delete third; // Delete in reverse order delete second; delete head; return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter