Run ❯
Get your
own
website
❯
Run Code
Ctrl+Alt+R
Change Orientation
Ctrl+Alt+O
Change Theme
Ctrl+Alt+D
Go to Spaces
Ctrl+Alt+P
#include
#include
struct Node { int data; struct Node *next; }; struct Node *createNode(int value) { struct Node *newNode = malloc(sizeof(struct Node)); if (newNode == NULL) { printf("Memory allocation failed\n"); exit(1); } newNode->data = value; newNode->next = NULL; return newNode; } // Adds a node at the front, and returns the new head struct Node *insertAtFront(struct Node *head, int value) { struct Node *newNode = createNode(value); newNode->next = head; // Step 1: point to the current head return newNode; // Step 2: the new node is the new head } void printList(struct Node *head) { struct Node *current = head; while (current != NULL) { printf("%d -> ", current->data); current = current->next; } printf("NULL\n"); } void freeList(struct Node *head) { while (head != NULL) { struct Node *next = head->next; free(head); head = next; } } int main() { struct Node *head = NULL; // An empty list head = insertAtFront(head, 30); printList(head); head = insertAtFront(head, 20); printList(head); head = insertAtFront(head, 10); printList(head); freeList(head); return 0; }
30 -> NULL
20 -> 30 -> NULL
10 -> 20 -> 30 -> NULL