I'm relatively new to programming as I've just started university. My assignment is to develop a program (by using a function and a linked list with pointers with integer elements) which does the following:
the function visits every element from the beginning. if the current element plus one is <= to the following element (eg. if the first one is i and the second one is j, j>=i+1), you have to complete the list by adding all the values between i and j-1.
if the current element is followed by an element <=, it is to be removed by the list and added to an array declared in the formal parameters. you also have to put in the formal parameters a counter for the deleted elements.
Added from comments:
If program is run with the second element being bigger than the first one[,] it usually crashes.
i have absolutely no clue what i'm doing wrong. sorry if i made any grammar mistakes, English is not my native language.
#include <stdio.h>
#include <stdlib.h>
struct list {
int value;
struct list * next_ptr;
};
void pre_insert(struct list ** ptrptr, int value) {
struct list * tmp_ptr;
tmp_ptr = *ptrptr;
*ptrptr = (struct list*)malloc(sizeof(struct list));
(*ptrptr)->value = value;
(*ptrptr)->next_ptr = tmp_ptr;
}
int complete_list_array(struct list * ptr, int * V, int * count) {
struct list * succ_ptr;
int i, k = 0;
while (ptr != NULL) {
if (ptr->next_ptr != NULL) {
succ_ptr = ptr->next_ptr;
if (ptr->value + 1 <= succ_ptr->value) {
for(i = 1; ptr->value + i <= succ_ptr->value; i++) { //
succ_ptr = succ_ptr->next_ptr;
ptr = ptr->next_ptr;
pre_insert(&ptr, ptr->value+ i);
}
ptr = ptr->next_ptr;
}
else if (ptr->value >= succ_ptr->value) {
ptr->next_ptr = succ_ptr->next_ptr;
V[k] = succ_ptr->value;
free(succ_ptr);
k++;
(*count)++;
ptr = ptr->next_ptr;
}
}
}
return (*count);
}
struct list * create_list(int N) {
struct list * first_ptr, * ptr;
int i;
if(N == 0) {
first_ptr = NULL;
}
else {
first_ptr = (struct list *)malloc(sizeof(struct list));
printf("Insert the first value:\n");
scanf("%d", &first_ptr->value);
ptr = first_ptr;
for(i = 2; i <= N; i++) {
ptr->next_ptr = (struct list *)malloc(sizeof(struct list));
ptr = ptr->next_ptr;
printf("Insert element number %d:\n", i);
scanf("%d", &ptr->value);
}
ptr->next_ptr = NULL;
}
return(first_ptr);
}
void visit(struct list * ptr) {
int i = 1;
while(ptr != NULL) {
printf("The element number %d in the list has value %d.\n", i, ptr->value);
ptr = ptr->next_ptr;
i++;
}
}
int main() {
struct list * first_ptr;
int N;
printf("Insert the number N of elements in the list.\n");
scanf("%d", &N);
first_ptr = create_list(N);
printf("Elements of the list.\n");
visit(first_ptr);
int * V, count = 0;
V = (int *)malloc(sizeof(int)* N);
count = complete_list_array(first_ptr, V, &count);
printf("count = %d", count);
}