nguyentruong98

Untitled

Nov 11th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.04 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. typedef struct Node
  5. {
  6.       char Name[80], Phone[80], Email[80];
  7.       struct Node* leftChild;
  8.       struct Node* rightChild;
  9.       struct Node* parent;
  10. }Node;
  11. Node* root;
  12. Node* makeNode(char *s1, char* s2, char* s3)
  13. {
  14.       Node*p = (Node*)malloc(sizeof(Node));
  15.       strcpy(p->Name,s1);
  16.       strcpy(p->Phone,s2);
  17.       strcpy(p->Email,s3);
  18.       p->parent = NULL;
  19.       p->leftChild = NULL;
  20.       p->rightChild = NULL;
  21.       return p;
  22. }
  23. void addNode(Node*p)
  24. {
  25.       if(root == NULL)
  26.       {
  27.             root = p;
  28.             return;
  29.       }
  30.       Node*q = root;
  31.       int cmp;
  32.       while(1)
  33.       {
  34.             if(q == NULL)
  35.             {
  36.                   q = p;
  37.                   return;
  38.             }
  39.             cmp = strcmp(q->Name,p->Name);
  40.             switch(cmp)
  41.             {
  42.                   case 0:
  43.                   return;
  44.                   case -1:
  45.                   q = q->rightChild;
  46.                   break;
  47.                   case 1:
  48.                   q = q->leftChild;
  49.                   break;
  50.             }
  51.       }
  52. }
  53. Node* findNode(char* Name, Node*p)
  54. {
  55.       if(p == NULL)
  56.       return NULL;
  57.       int cmp;
  58.       cmp = strcmp(p->Name,Name);
  59.       Node* q;
  60.       switch(cmp)
  61.       {
  62.             case 0:
  63.             return p;
  64.             case 1:
  65.             q = findNode(Name, p->leftChild);
  66.             return q;
  67.             break;
  68.             case -1:
  69.             q = findNode(Name, p->rightChild);
  70.             return q;
  71.             break;
  72.       }
  73. }
  74. void printbst(Node* p)
  75. {
  76.       if(root == NULL)
  77.       return;
  78.       printf("%s %s %s", p->Name, p->Phone, p->Email);
  79.       printbst(p->leftChild);
  80.       printbst(p->rightChild);
  81.       return;
  82. }
  83. int main()
  84. {
  85.       FILE *f;
  86.       f = fopen("phonebook.txt", "r");
  87.       if (f == NULL)
  88.       {
  89.             printf("ERROR");
  90.       }
  91.       else
  92.       {
  93.             char s1[80], s2[80], s3[80];
  94.             fscanf(f, "%s %s %s", s1, s2, s3);
  95.             Node* newNode = makeNode(s1,s2,s3);
  96.             addNode(newNode);
  97.       }
  98.       printbst(root);
  99.       return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment