Dobra poradzilem sobie z tym, jeśli ktoś ma pomysł jak napisać funkcję insert_before, dodającą element przed określonym elementem to będzie fajnie(w kodzie jest funkcja którą zrobiłem dodającą element po określonym elemencie-insert_after)
#include <stdio.h>
#include <stdlib.h>
typedef struct list {
int data;
struct list* next;
} list_element;
int push_front(list_element** head, int n)
{
list_element* tmp = (list_element*)malloc(sizeof(list_element));
if (tmp == NULL) {
puts("no memory");
return 0;
}
tmp->data = n;
tmp->next = *head;
*head = tmp;
return 1;
}
void print(list_element** head)
{
if (*head == NULL)
return;
printf("\t%d", (*head)->data);
print(&(*head)->next);
}
void size(list_element* head)
{
int amount = 0;
for (; head != NULL; head = head->next)
++amount;
printf("%d", amount);
}
void pop_front(list_element** head)
{
list_element* tmp;
tmp = *head;
*head = (*tmp).next;
free(tmp);
}
void push_back(list_element** head, int n)
{
list_element* tmp = (list_element*)malloc(sizeof(list_element));
if (tmp == NULL) {
puts("no memory");
return;
}
tmp->data = n;
tmp->next = NULL;
if (*head == NULL) {
*head = tmp;
}
else {
list_element** last = &(*head)->next;
while (*last != NULL)
last = &(*last)->next;
*last = tmp;
}
}
void pop_back(list_element** head)
{
list_element* tmp = *head;
list_element* preavious = NULL;
while (tmp->next) {
preavious = tmp;
tmp = tmp->next;
}
if (preavious == NULL) {
free(head);
head = NULL;
}
else {
preavious->next = NULL;
free(tmp);
}
}
void insert_after(list_element* head, int n)
{
int choice, i;
printf("\nafter element(1,2..):");
scanf("%d", &choice);
for (i = 1; i < choice; ++i) {
head = head->next;
}
list_element* tmp = (list_element*)malloc(sizeof(list_element));
tmp->data = n;
tmp->next = head->next;
head->next = tmp;
}
void options()
{
puts("1:push_front");
puts("2:print list");
puts("3:size list");
puts("4:pop_front");
puts("5:push_back");
puts("6:pop_back");
puts("7:insert_after");
puts("8:clear list");
puts("0:end program");
}
int main()
{
list_element* first = NULL;
int choice;
int end_program;
while (end_program != 0) {
options();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nGive me a number to add:");
scanf("%d", &choice);
push_front(&first, choice);
break;
case 2:
print(&first);
break;
case 3:
size(first);
break;
case 4:
pop_front(&first);
break;
case 5:
printf("\nGive me a number to add:");
scanf("%d", &choice);
push_back(&first, choice);
break;
case 6:
pop_back(&first);
break;
case 7:
printf("\nGive me a number to add:");
scanf("%d", &choice);
insert_after(first, choice);
break;
case 8:
free(first);
first = NULL;
break;
default:
puts("Blad!");
break;
}
printf("\nyou continue?(0 - end program):");
scanf("%d", &end_program);
}
return 0;
}