Advertisement
Guest User

Untitled

a guest
Mar 11th, 2014
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. //
  2. //  Symtab.cpp
  3. //  assembly
  4. //
  5. //  Created by Ethan Laur on 3/11/14.
  6. //  Copyright (c) 2014 Ethan Laur. All rights reserved.
  7. //
  8.  
  9. #include "Symtab.h"
  10. #include <string.h>
  11. #include <stdio.h>
  12.  
  13. int Symtab::findNodeByName_private(char *sym_name)
  14. {
  15.     Symtab_struct *list = head;
  16.     int i;
  17.     for (i = 0; list != NULL; list = list->next, i++)
  18.         if (strcmp(sym_name, list->sym_name) == 0)
  19.             break;
  20.     return list == NULL ? -1 : i;
  21. }
  22.  
  23. Symtab_struct *Symtab::findNodeByNumber(int sym_id)
  24. {
  25.     Symtab_struct *list = head;
  26.     int i;
  27.     if (sym_id < 0) return NULL;
  28.     for (i = 0; i < sym_id && list != NULL; list = list->next, i++);
  29.     return list;
  30. }
  31.  
  32. void Symtab::insertNode(char *sym_name, int sym_location)
  33. {
  34.     Symtab_struct *node = (Symtab_struct *)malloc(sizeof(Symtab_struct));
  35.     strcpy(node->sym_name, sym_name);
  36.     node->sym_location = sym_location;
  37.     if (findNodeByName_private(sym_name) >= 0)
  38.     {
  39.         printf("[WARN in Symtab::insertNode] Redefinition of symbol %s is ignored\n", sym_name);
  40.         return; //don't add it twice
  41.     }
  42.     if (head == NULL) //empty list
  43.     {
  44.         head = tail = node;
  45.     }
  46.     else
  47.     {
  48.         tail->next = node;
  49.         tail = node;
  50.     }
  51.     tail->next = NULL;
  52. }
  53.  
  54. void Symtab::deleteNode(char *sym_name)
  55. {
  56.     Symtab_struct *parent, *child, *node;
  57.     int nodenum = findNodeByName_private(sym_name);
  58.     parent = findNodeByNumber(nodenum - 1);
  59.     node = findNodeByNumber(nodenum);
  60.     child = findNodeByNumber(nodenum + 1);
  61.     if (nodenum == 0) //deleting the head
  62.     {
  63.         free(node);
  64.         head = child;
  65.     }
  66.     else if (node == tail) //delete the tail
  67.     {
  68.         free(node);
  69.         tail = parent;
  70.     }
  71.     else if (node == NULL) //node does not exist
  72.     {
  73.         printf("[WARN in Symtab::deleteNode] Attempting to delete a symbol %s that does not exist\n",
  74.               sym_name);
  75.     }
  76.     else //somewhere in mid list
  77.     {
  78.         parent->next = child;
  79.         free(node);
  80.     }
  81. }
  82.  
  83. Symtab_struct *Symtab::findNodeByName(char *sym_name)
  84. {
  85.     return findNodeByNumber(findNodeByName_private(sym_name));
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement