Facebook
From Crippled Iguana, 1 Year ago, written in Plain Text.
This paste is a reply to Drzewo Binarne from a - view diff
Embed
Download Paste or View Raw
Hits: 120
  1. #include <stdio.h>
  2.  
  3. struct wezel
  4. {
  5.         int licznik, liczba;
  6.         struct wezel *prawy;
  7.         struct wezel *lewy;
  8. };
  9.  
  10. struct wezel* wkorzen = NULL;
  11.  
  12. struct wezel *nowy_wezel(int x)
  13. {
  14.         struct wezel *wsk = malloc(sizeof(struct wezel));
  15.         wsk->licznik = 1;
  16.         wsk->liczba = x;
  17.         wsk->lewy = NULL;
  18.         wsk->prawy = NULL;
  19.         return wsk;
  20. }
  21.  
  22. void dodaj(int x)
  23. {
  24.         if(wkorzen == NULL)
  25.         {
  26.                 wkorzen = nowy_wezel(x);
  27.                 return;
  28.         }
  29.        
  30.         struct wezel *p1 = wkorzen;
  31.         struct wezel *p2;
  32.        
  33.         while(p1 != NULL)
  34.         {
  35.                 p2 = p1;
  36.                        
  37.                 if(p1->liczba < x)
  38.                 {
  39.                         p1 = p1->prawy;
  40.                 }
  41.                 else if(p1->liczba > x)
  42.                 {
  43.                         p1 = p1->lewy;
  44.                 }
  45.                 else
  46.                 {
  47.                         p1->licznik++; 
  48.                         return;
  49.                 }
  50.         }
  51.        
  52.         if(p2->liczba < x)
  53.         {
  54.                 p2->prawy = nowy_wezel(x);
  55.         }
  56.         else
  57.         {
  58.                 p2->lewy = nowy_wezel(x);
  59.         }
  60. }
  61.  
  62. void pisz(struct wezel *wsk)
  63. {
  64.         if(wsk == NULL) return;
  65.         pisz(wsk->lewy);
  66.         printf("liczba: %d licznik:%d\n", wsk->liczba, wsk->licznik);
  67.         pisz(wsk->prawy);
  68. }
  69.  
  70. int main(void)
  71. {
  72.         dodaj(5);dodaj(17);dodaj(2);dodaj(12);dodaj(5);dodaj(7);
  73.         pisz(wkorzen);
  74. }