Linked List Example C
unknown
c_cpp
a year ago
1.6 kB
5
Indexable
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; struct LinkedList { struct Node* head; }; struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (newNode == NULL) { printf("Memory allocation error\n"); exit(EXIT_FAILURE); } newNode->data = data; newNode->next = NULL; return newNode; } void append(struct LinkedList* list, int data) { struct Node* new_node = createNode(data); if (list->head == NULL) { list->head = new_node; } else { struct Node* current = list->head; while (current->next != NULL) { current = current->next; } current->next = new_node; } } void print(struct LinkedList* list) { struct Node* current = list->head; while (current != NULL) { printf("%d\n", current->data); current = current->next; } } void freeList(struct LinkedList* list) { struct Node* current = list->head; while (current != NULL) { struct Node* temp = current; current = current->next; free(temp); } list->head = NULL; } int main() { struct LinkedList list = {NULL}; append(&list, 1); append(&list, 2); append(&list, 3); struct Node* current = list.head; while (current != NULL) { printf("%d\n", current->data); current = current->next; } printf("%d\n", current->data); freeList(&list); return 0; }
Editor is loading...