Advertisement
Guest User

Untitled

a guest
Nov 18th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.86 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define PROMPT_COMMAND "Enter command:\n"
  6. #define COMMAND_FAIL "Command failed.\n"
  7.  
  8. typedef char * string;
  9. typedef enum { SUCCESS, FAIL } result;
  10. typedef enum { INTEGER, DOUBLE, STRING } item_tag;
  11.  
  12. typedef struct item_t *item_ptr;
  13.  
  14. typedef struct item_t {
  15.     item_tag tag;
  16.     union {
  17.         int i;
  18.         double d;
  19.         string s;
  20.     } value;
  21.     item_ptr next_item;
  22. } item;
  23.  
  24. item *head;
  25.  
  26. /*
  27. track number of nodes on stack
  28. */
  29. int STACK_SIZE = 0;
  30.  
  31. /*
  32. push item i onto stack
  33. if successful returns SUCCESS
  34. else returns FAIL
  35. */
  36. result Push(item i) {
  37.     item *temp;
  38.     temp = malloc(sizeof(item));
  39.    
  40.     temp->value = i.value;
  41.     temp->next_item = head;
  42.    
  43.     head = temp;
  44.  
  45.     free(temp);
  46.     STACK_SIZE++;
  47.     return SUCCESS;
  48. }
  49.  
  50. /*
  51. retrieves topmost item from stack and stores in location *ip
  52. if successful returns SUCCESS
  53. else returns FAIL
  54. */
  55. result Pop(item *ip) {
  56.     if ( head->next_item == NULL ) {
  57.         printf(COMMAND_FAIL);
  58.         return FAIL;
  59.     } else {
  60.  
  61.         ip->value = head->value;
  62.         ip->next_item = NULL;
  63.  
  64.         head = head->next_item;
  65.  
  66.         STACK_SIZE--;
  67.         return SUCCESS;
  68.     }
  69. }
  70.  
  71. /*
  72. prints contents of top item on stack
  73. */
  74. result Print() {
  75.     if ( STACK_SIZE == 0 ) {
  76.         printf(COMMAND_FAIL);
  77.         return FAIL;
  78.     } else {
  79.         if ( head->tag == STRING ) {
  80.             printf("Head value is %s \n", head->value.s);
  81.         } else if ( head->tag == INTEGER ) {
  82.             printf("Head value is %i \n", head->value.i);
  83.         } else if ( head->tag == DOUBLE ) {
  84.             printf("Head value is %f \n", head->value.d);
  85.         }
  86.     }
  87.     return SUCCESS;
  88. }
  89.  
  90. int main() {
  91.  
  92.     item *temp1;
  93.     temp1 = malloc(sizeof(item));
  94.  
  95.     item testI;
  96.     testI.value.i = 5;
  97.  
  98.     Push(testI);
  99.     Print();
  100.  
  101.     testI.value.i = 7;
  102.     Push(testI);
  103.     Print();
  104.  
  105.     testI.value.i = 3;
  106.     Push(testI);
  107.     Print();
  108.  
  109.     Pop(temp1);
  110.     printf("Popped value is: %i\n", temp1->value.i);
  111.     Print();
  112.  
  113.     return 0;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement