Finished task 3, closes #8

This commit is contained in:
Inex Code 2020-05-05 17:18:49 +03:00
parent 7bf35f4310
commit 1d89f16b65
1 changed files with 88 additions and 0 deletions

88
task3/task3.c Normal file
View File

@ -0,0 +1,88 @@
#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;
}