Advertisement
davide1409

stack.c

Nov 4th, 2021
1,016
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. #include "stack.h"
  2. #include <stdlib.h>
  3. #include <assert.h>
  4.  
  5. struct node* top(struct stack *pila){
  6.     if(pila == NULL)
  7.         return NULL;
  8.  
  9.     return pila->sp;
  10. }
  11.  
  12.  
  13. int init_stack(struct stack *pila){
  14.     if(pila == NULL)
  15.         return -1;
  16.  
  17.     pila->sp = NULL; // pila vuota
  18.     return 0; // inizializzazione avvenuta con successo
  19. }
  20.  
  21. int empty(struct stack *pila){
  22.     if(pila == NULL)
  23.         return -1;
  24.  
  25.     return (pila->sp == NULL);
  26. }
  27.  
  28.  
  29. int push(struct stack *pila, int val){
  30.     if(pila == NULL){
  31.         return -1;
  32.     }
  33.  
  34.     struct node *nodo = malloc(sizeof(*nodo)); // creo il nodo
  35.     if(nodo == NULL){
  36.         return -1;
  37.     }
  38.    
  39.     // inizializzato il nodo
  40.     nodo->val = val;
  41.     nodo->next = NULL;
  42.     nodo->prev = NULL;
  43.  
  44.     if(pila->sp != NULL){
  45.         pila->sp->next = nodo;
  46.         nodo->prev = pila->sp;
  47.     } // se la pila è vuota devo solo aggiornare top
  48.  
  49.     pila->sp = nodo;
  50.  
  51.     return 0; // push avvenuta con successo
  52. }
  53.  
  54.  
  55. struct node* pop(struct stack *pila){
  56.     if(pila == NULL)
  57.         return NULL;
  58.    
  59.  
  60.     // la pila è non nulla
  61.  
  62.     struct node *top = pila->sp;
  63.    
  64.     if(pila->sp != NULL){
  65.         pila->sp = pila->sp->prev; // la nuova cima è il nodo precendete alla vecchia
  66.         if(pila->sp != NULL){
  67.             pila->sp->next->prev = NULL; // il next della vecchia cima(essendo tale) era già null -> vecchia cima staccata
  68.             pila->sp->next = NULL; // ora ho la nuova cima
  69.         }
  70.     }
  71.  
  72.     return top;
  73. }
  74.  
  75. int get_value(struct stack *pila, struct node* nodo){
  76.     if(pila == NULL)
  77.         assert("Stack nullo\n");
  78.  
  79.     if(nodo == NULL)
  80.         assert("Nodo nullo\n");
  81.  
  82.     int value = nodo->val;
  83.  
  84.     if(nodo != pila->sp){ // avviene <=> nodo proviene da una pop
  85.         free(nodo);
  86.     }
  87.  
  88.     return value;
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement