88 lines
1.7 KiB
C
88 lines
1.7 KiB
C
|
#include <errno.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
|
||
|
typedef struct node {
|
||
|
int val;
|
||
|
struct node *next;
|
||
|
} NODE;
|
||
|
|
||
|
NODE *init_node(int val) {
|
||
|
NODE *buf;
|
||
|
buf = malloc(sizeof(NODE));
|
||
|
if (buf == NULL) {
|
||
|
fprintf(stderr, "Error allocating node\n");
|
||
|
return NULL;
|
||
|
}
|
||
|
buf->val = val;
|
||
|
buf->next = NULL;
|
||
|
return buf;
|
||
|
}
|
||
|
|
||
|
void add_node(NODE *list, int val) {
|
||
|
NODE *node = init_node(val);
|
||
|
if (node == NULL) {
|
||
|
return;
|
||
|
}
|
||
|
for (; list->next != NULL; list = list->next)
|
||
|
;
|
||
|
list->next = node;
|
||
|
}
|
||
|
|
||
|
void del_node(NODE *list, NODE *node) {
|
||
|
for (; list->next != NULL; list = list->next) {
|
||
|
if (list->next == node) {
|
||
|
list->next = (list->next)->next;
|
||
|
free(node);
|
||
|
return;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
int count_length(NODE *list) {
|
||
|
int counter = 1;
|
||
|
for (; list->next != NULL; list = list->next) {
|
||
|
counter++;
|
||
|
}
|
||
|
return counter;
|
||
|
}
|
||
|
|
||
|
void print_list(NODE *list) {
|
||
|
for (; list->next != NULL; list = list->next) {
|
||
|
printf("%d\n", list->val);
|
||
|
}
|
||
|
printf("%d\n", list->val);
|
||
|
}
|
||
|
|
||
|
NODE *reverse_list(NODE *list) {
|
||
|
NODE *prev = NULL;
|
||
|
NODE *next = list->next;
|
||
|
while (next != NULL) {
|
||
|
list->next = prev;
|
||
|
prev = list;
|
||
|
list = next;
|
||
|
next = list->next;
|
||
|
}
|
||
|
list->next = prev;
|
||
|
return list;
|
||
|
}
|
||
|
|
||
|
int main() {
|
||
|
NODE *list = init_node(4);
|
||
|
add_node(list, 5);
|
||
|
print_list(list);
|
||
|
printf("\n[%d]\n\n", count_length(list));
|
||
|
del_node(list, list->next);
|
||
|
print_list(list);
|
||
|
printf("\n[%d]\n\n", count_length(list));
|
||
|
add_node(list, 1);
|
||
|
add_node(list, 2);
|
||
|
add_node(list, 3);
|
||
|
add_node(list, 4);
|
||
|
print_list(list);
|
||
|
printf("\n[%d]\n\n", count_length(list));
|
||
|
list = reverse_list(list);
|
||
|
print_list(list);
|
||
|
printf("\n[%d]\n\n", count_length(list));
|
||
|
return 0;
|
||
|
}
|