daily pastebin goal
57%
SHARE
TWEET

Untitled

a guest Dec 16th, 2018 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define max(a, b) ((a > b) ? a : b)
  5. #define min(a, b) ((a < b) ? a : b)
  6.  
  7. struct stack{
  8.     int *data;
  9.     int cap, top;
  10. };
  11. //void swapEl (int *i, int *j);
  12. void initStack (int, struct stack*);
  13. void push (struct stack*, int);
  14. void swap (struct stack*);
  15. int pop (struct stack*);
  16.  
  17. int main(int argc, char *argv[]) {
  18.     int n;
  19.     scanf("%i ", &n);
  20.     struct stack st;
  21.     initStack (n, &st);
  22.     for (int i = 0; i < n; i++) {
  23.         char *op = (char*)malloc(sizeof(char) * 6);
  24.         gets(op)
  25.         int x;
  26.         if (!strncmp(op, "CONST", 5)) {
  27.             scanf ("%i", &x);
  28.             push (&st, x);
  29.         } else if (!strncmp(op, "ADD", 3))
  30.             push(&st, pop(&st) + pop(&st));
  31.         else if (!strncmp(op, "SUB", 3))
  32.             push(&st, pop(&st) - pop(&st));
  33.         else if (!strncmp(op, "MUL", 3))
  34.             push(&st, pop(&st) * pop(&st));
  35.         else if (!strncmp(op, "DIV", 3))
  36.             push(&st, pop(&st) / pop(&st));
  37.         else if (!strncmp(op, "MAX", 3))
  38.             push(&st, max(pop(&st), pop(&st)));
  39.         else if (!strncmp(op, "MIN", 3))
  40.             push(&st, min(pop(&st), pop(&st)));
  41.         else if (!strncmp(op, "NEG", 3))
  42.             push(&st, -pop(&st));
  43.         else if (!strncmp(op, "DUP", 3))
  44.             push(&st, st.data[st.top]);
  45.         else if (!strncmp(op, "SWAP", 4))
  46.             swap(&st);
  47.         free(op);
  48.     }
  49.     int fin = pop(&st);
  50.     printf("%i", fin);
  51.     return 0;
  52. }
  53.  
  54. void initStack (int n, struct stack *st){
  55.     st->data = (int*)malloc(sizeof(int) * n);
  56.     st->cap = n;
  57.     st->top = 0;
  58. }
  59.  
  60. int pop (struct stack *arr){
  61.     arr->top--;
  62.     return arr->data[arr->top];
  63. }
  64.  
  65. void push (struct stack *arr, int x){
  66.     arr->data[arr->top] = x;
  67.     arr->top++;
  68. }
  69.  
  70. void swap (struct stack *arr){
  71.     int e1 = pop(arr);
  72.     int e2 = pop(arr);
  73.     push(arr, e1);
  74.     push(arr, e2);
  75. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top