AM i starting the first of this code correctly?
@dan815
before when i made a linked list, we used nodes to long the values. which made it easier to traverse the list. but without it, i'm not quite sure how to traverse the list.
Well, I would start with checking if the list is full. If it is, you can't insert without doubling the size first.
you traverse this list like you would any array: list *ls = ...; for (int i = 0; i < ls->size; ++i) { int val = ls->sortedList[i]; ... }
anyways, first you want to check if it's full (size == maxSize); if so, you want to reallocate it with double its previous capacity (maxSize) if (ls->size == ls->maxSize) { ls->maxSize *= 2; ls->sortedList = (int *) realloc(ls->sortedList, ls->maxSize); }
now to find where to insert it, you need to loop through until you find the point where the elements become bigger than that which we want to insert; basically, if we had 1 3 4 8 10, and we wanted to insert 7, we'd loop through 1, 3, 4, and then once we got to 8 we would notice that 7 needs to be inserted in between 4 and 8
so: int i; for (i = 0; i < ls->size; ++i) { if (ls->sortedList[i] <= val) { /* val should be inserted between the elements at i-1, i */ break; } } /* shift over by 1 the elements from i to the end to make room for val */ for (int j = ls->size - 1; j >= i; --j) { ls->sortedList[j+1] = ls->sortedList[j]; } /* insert val at i */ ls->sortedList[i] = val;
Join our real-time social learning platform and learn together with your friends!