SHARE
TWEET

Untitled

a guest Oct 10th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // import modules
  2. #include <stdio.h>
  3. #include <limits.h>
  4. #include <stdlib.h>
  5.  
  6. // define Stack struct
  7. struct Stack {
  8.         int* arr;
  9.         int top;
  10.         unsigned length;
  11. };
  12.  
  13. // create stack function
  14. struct Stack* createStack(unsigned len) {
  15.         // create stack
  16.         struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
  17.  
  18.         // insert values
  19.         stack->length = len;
  20.         stack->top = -1;
  21.         stack->arr = (int*)malloc(stack->length * sizeof(int));
  22.  
  23.         // return stack
  24.         return stack;
  25. }
  26.  
  27. // check stack is full
  28. int isFull(struct Stack* stack) {
  29.         // check full
  30.         return stack->top == stack->length - 1;
  31. }
  32.  
  33. // check stack is empty
  34. int isEmpty(struct Stack* stack) {
  35.         // check empty
  36.         return stack->top == -1;
  37. }
  38.  
  39. // push item into the stack
  40. int push(struct Stack* stack, int i) {
  41.         // check stack is full
  42.         if (isFull(stack)) {
  43.                 return 0;
  44.         }
  45.  
  46.         // insert item
  47.         stack->arr[++stack->top] = i;
  48.  
  49.         // return top index
  50.         return stack->top;
  51. }
  52.  
  53. // pop from stack
  54. int pop(struct Stack* stack) {
  55.         // check stack is empty
  56.         if (isEmpty(stack)) {
  57.                 return 0;
  58.         }
  59.  
  60.         // return top value
  61.         return stack->arr[stack->top--];
  62. }
  63.  
  64. // main
  65. int main(void) {
  66.         // create a stack
  67.         struct Stack* stack = createStack(100);
  68.  
  69.         // push items
  70.         push(stack, 10);
  71.         push(stack, 20);
  72.         push(stack, 30);
  73.  
  74.         // print length
  75.         printf("length: %d\n", stack->length);
  76.  
  77.         // pop item
  78.         printf("pop: %d\n", pop(stack));
  79.  
  80.         return 0;
  81. }
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