Ask your own question, for FREE!
Computer Science 25 Online
OpenStudy (curry):

AM i starting the first of this code correctly?

OpenStudy (curry):

@dan815

OpenStudy (curry):

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.

OpenStudy (e.mccormick):

Well, I would start with checking if the list is full. If it is, you can't insert without doubling the size first.

OpenStudy (anonymous):

you traverse this list like you would any array: list *ls = ...; for (int i = 0; i < ls->size; ++i) { int val = ls->sortedList[i]; ... }

OpenStudy (anonymous):

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); }

OpenStudy (anonymous):

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

OpenStudy (anonymous):

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;

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!