Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.70 KB | None | 0 0
  1. #ifndef STACK_H
  2. #define STACK_H
  3.  
  4. #include <stdlib.h>
  5.  
  6. typedef struct node {
  7.     void *value;
  8.     struct node *next;
  9. } node;
  10.  
  11. typedef struct stack {
  12.     node *head;
  13.     int size;
  14. } stack;
  15.  
  16. void push(stack *stk, void *val) {
  17.     node *n = malloc(sizeof(node));
  18.     n->value = val;
  19.     n->next = stk->head == NULL ? NULL : stk->head; //either point to old head or become head
  20.     stk->head = n; //become current head
  21.     stk->size++;
  22. }
  23.  
  24. void *pop(stack *stk) {
  25.     if (stk->head == NULL) { //empty
  26.         return NULL;
  27.     }
  28.     node *temp = stk->head; //temp pointer to old head
  29.     void *val = temp->value; //get value
  30.     stk->head = temp->next; //set new head
  31.     free(temp); //free old head
  32.     stk->size--;
  33.     return val;
  34. }
  35.  
  36. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement