I have an assignment that requires to implement Singly Linked Lists in C and write a few functions. I'm bound to the way my lecture does it.. the struct and parameters of the function are determined so I can't change any of that.
The function is supposed to insert a list element with the value v at position pos into the list l.
I'll post what I was given first and my attempt after:
struct le {
int value;
struct le *next;
};
typedef struct le listelement;
typedef listelement *list;
int insert_pos(int v, int pos, list *l);
Again, I have to work with that the way it is. My attempt for the function is as follows:
int insert_pos(int v, int pos, list *l) {
if (*l == NULL) {
printf("empty");
return -1;
} else {
listelement *new;
new = malloc(sizeof(listelement));
while (pos > 0) {
l = l -> next;
pos--;
}
new -> value = v;
new -> next = *l;
*l = new;
}
}
The
l = l -> next;
causes problems in my compiler because it expects a pointer but changing it to *l doesn't do anything. The whole thing is probably a mess..