Advertisement
Guest User

Untitled

a guest
May 21st, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. void countDuplicates(struct node* head) {
  2.     struct numberCounts {
  3.         int value;
  4.         int count;
  5.     };
  6.     typedef struct numberCounts numberCounts;
  7.    
  8.     struct node *temp = head;
  9.    
  10.     int length = 0;
  11.     while(temp != NULL) {
  12.         length++;
  13.         temp = temp->next;
  14.     }
  15.    
  16.     numberCounts *numCts = (numberCounts*) calloc (length, sizeof(numberCounts));
  17.     length = 0;
  18.    
  19.     temp = head;
  20.     while(temp != NULL) {
  21.         int i = 0;
  22.        
  23.         for(i = 0; i < length; i++)
  24.             if (numCts[i].value == temp->data) {
  25.                 numCts[i].count++;
  26.                 i = -1;
  27.                 break;
  28.             }
  29.        
  30.         if (i != -1) {
  31.             length++;
  32.             numCts = (numberCounts*) realloc (length, sizeof(numberCounts));
  33.             numCts[length - 1].value = temp->data;
  34.             numCts[length - 1].count = 1;
  35.         }
  36.        
  37.         temp = temp->next;
  38.     }
  39.    
  40.    
  41.     for (int i = length - 1; i > 0; i--) {
  42.         for (int j = 1; j <= i; j++) {
  43.             if (numCts[j-1].value > numCts[j].value) {
  44.                 int tempVal = numCts[j-1].value;
  45.                 int tempCount = numCts[j-1].count;
  46.                
  47.                 numCts[j-1].value = numCts[j].value;
  48.                 numCts[j-1].count = numCts[j].count;
  49.                
  50.                 numCts[j].value = temp->value;
  51.                 numCts[j].count = temp->count;
  52.             }
  53.         }
  54.     }
  55.    
  56.     for (int i = 0; i < length; i++)
  57.         printf("The %d data was found %d times\n\n", numCts[i].value, numCts[i].count);
  58.    
  59.     free(numCts);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement