#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// Insert at end function
void insertAtEnd(struct Node** head, int value) {
struct Node* newNode = createNode(value);
if (*head == NULL) {
*head = newNode; // empty list, new node is head
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next; // advance to last node
}
current->next = newNode; // link new node at end
}
// Print list function
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("null\n");
}
int main() {
struct Node* head = createNode(1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtEnd(&head, 4); // insert value 4 at end
printList(head);
return 0;
}while (current->next != NULL) {
current = current->next; // advance to last node
}
advance current to last node to find where to insert
current->next = newNode; // link new node at end
attach new node after last node to extend list
if (*head == NULL) {
*head = newNode; // empty list, new node is head
return;
}
handle empty list by making new node the head