I am making a function that lists an array and says how many times each element appears.
What I have thought of on my own so far is i should loop through the array and t
At first you must define a list with the integers you have and their number of appearances
struct linked_list {
int value;
int numOf;
linked_list *next;
};
then you must have the functions to operate that list, like creating a list, pushing an item to it, finding a node in that list and print it the list.
linked_list* newItem(int value) {
linked_list * temp = (linked_list *)malloc(sizeof(linked_list));
(*temp).value = value;
(*temp).numOf = 1;
return temp;
}
linked_list* findItem(linked_list *head, int value) {
linked_list *counter = head;
while (counter != NULL && (*counter).value != value) {
counter = (*counter).next;
}
return counter;
}
void pushToList(linked_list **head, linked_list *item) {
(*item).next = *head;
*head = item;
}
void printList(linked_list *head) {
while (head != NULL) {
printf("%d:%d\n", (*head).value, (*head).numOf);
head = (*head).next;
}
}
You must study lists in order to understand how do they operate. Then your code logic goes like this:
linked_list *duplicate = NULL;
int i;
int list[11] = { 1, 2, 3, 4, 1, 2, 3, 4, 0, 1, 2 };
for (i = 0; i < 11; i++) {
linked_list *current = findItem(duplicate, list[i]);
if (current == NULL)
pushToList(&duplicate, newItem(list[i]));
else
(*current).numOf++;
}
printList(duplicate);
while (1);
return 0;
(I must free the list but I didn't in this code :P)
I make a list with the items/elements that may be duplicate. I start from the beginning of the array. I check the first element of the array and then I check if it is on the duplicate list. If I can't find it in the list, I make a new record to the duplicate list with 1 number of appearances. Then I check the rest, if they appear in the list I add the number of appearances by one, if they are not, I make a new record. At the end my list will have every number and their number of appearances.
This code takes O(n) steps if your data difference is a constant. If your data difference grows with the number of elements it would take more steps.
This approach is better than sorting algorithms in many occasions in terms of number of step to execute and memory allocation.