Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define PROMPT_COMMAND "Enter command:\n"
- #define COMMAND_FAIL "Command failed.\n"
- typedef char * string;
- typedef enum { SUCCESS, FAIL } result;
- typedef enum { INTEGER, DOUBLE, STRING } item_tag;
- typedef struct item_t *item_ptr;
- typedef struct item_t {
- item_tag tag;
- union {
- int i;
- double d;
- string s;
- } value;
- item_ptr next_item;
- } item;
- item *head;
- /*
- track number of nodes on stack
- */
- int STACK_SIZE = 0;
- /*
- push item i onto stack
- if successful returns SUCCESS
- else returns FAIL
- */
- result Push(item i) {
- item *temp;
- temp = malloc(sizeof(item));
- temp->value = i.value;
- temp->next_item = head;
- head = temp;
- free(temp);
- STACK_SIZE++;
- return SUCCESS;
- }
- /*
- retrieves topmost item from stack and stores in location *ip
- if successful returns SUCCESS
- else returns FAIL
- */
- result Pop(item *ip) {
- if ( head->next_item == NULL ) {
- printf(COMMAND_FAIL);
- return FAIL;
- } else {
- ip->value = head->value;
- ip->next_item = NULL;
- head = head->next_item;
- STACK_SIZE--;
- return SUCCESS;
- }
- }
- /*
- prints contents of top item on stack
- */
- result Print() {
- if ( STACK_SIZE == 0 ) {
- printf(COMMAND_FAIL);
- return FAIL;
- } else {
- if ( head->tag == STRING ) {
- printf("Head value is %s \n", head->value.s);
- } else if ( head->tag == INTEGER ) {
- printf("Head value is %i \n", head->value.i);
- } else if ( head->tag == DOUBLE ) {
- printf("Head value is %f \n", head->value.d);
- }
- }
- return SUCCESS;
- }
- int main() {
- item *temp1;
- temp1 = malloc(sizeof(item));
- item testI;
- testI.value.i = 5;
- Push(testI);
- Print();
- testI.value.i = 7;
- Push(testI);
- Print();
- testI.value.i = 3;
- Push(testI);
- Print();
- Pop(temp1);
- printf("Popped value is: %i\n", temp1->value.i);
- Print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement