57 lines
1.2 KiB
C
57 lines
1.2 KiB
C
#pragma once
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
/** Linked list data structure
|
|
*/
|
|
|
|
struct ListNode {
|
|
int val;
|
|
struct ListNode *next;
|
|
};
|
|
|
|
struct ListNode *list_create(int val) {
|
|
struct ListNode *node = malloc(sizeof(struct ListNode));
|
|
node->next = NULL;
|
|
node->val = val;
|
|
return node;
|
|
}
|
|
|
|
struct ListNode *list_insert(struct ListNode *list, int val) {
|
|
if (list == NULL) {
|
|
list = list_create(val);
|
|
return list;
|
|
} else {
|
|
struct ListNode *tail = list_create(val);
|
|
struct ListNode *current = list;
|
|
while (current->next != NULL) {
|
|
current = current->next;
|
|
}
|
|
current->next = tail;
|
|
return list;
|
|
}
|
|
}
|
|
|
|
void list_clear(struct ListNode *list) {
|
|
struct ListNode *current = list;
|
|
if (current == NULL) {
|
|
return;
|
|
}
|
|
while (current->next != NULL) {
|
|
struct ListNode *next = current->next;
|
|
free(current);
|
|
current = next;
|
|
}
|
|
}
|
|
|
|
void list_print(struct ListNode *list) {
|
|
struct ListNode *current = list;
|
|
printf("list: ");
|
|
while (current != NULL) {
|
|
printf("%d->", current->val);
|
|
current = current->next;
|
|
}
|
|
printf("\n");
|
|
}
|