Untitled
unknown
c_cpp
a year ago
1.4 kB
6
Indexable
#include <stdio.h> #include <stdlib.h> // Define the structure for a node in the linked list struct Node { int data; struct Node* next; }; // Function to create a new node with given data struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; return newNode; } // Function to insert a node at the end of the list void insertAtEnd(struct Node** head, int data) { struct Node* newNode = createNode(data); if (*head == NULL) { // If the list is empty, the new node becomes the head *head = newNode; } else { // Traverse the list to find the last node struct Node* last = *head; while (last->next != NULL) { last = last->next; } // Insert the new node at the end last->next = newNode; } } // Function to print the linked list void printList(struct Node* node) { while (node != NULL) { printf("%d -> ", node->data); node = node->next; } printf("NULL\n"); } int main() { struct Node* head = NULL; // Insert 5 elements into the list insertAtEnd(&head, 10); insertAtEnd(&head, 20); insertAtEnd(&head, 30); insertAtEnd(&head, 40); insertAtEnd(&head, 50); // Print the linked list printf("The created linked list is: \n"); printList(head); return 0; }
Editor is loading...
Leave a Comment