adding element at the end in linkedlist...
Thu Oct 17 2024 13:33:50 GMT+0000 (Coordinated Universal Time)
Saved by
@E23CSEU1151
#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;
}
content_copyCOPY
Comments