Advertisement
Guest User

stack.c

a guest
Jun 24th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "stack.h"
  4.  
  5. int main()
  6. {
  7.     /* Nodes */
  8.     int dado1 = 7, dado2 = 3, dado3 = 3, dado4 = 1, tmp;
  9.    
  10.     /* Stack */
  11.     Stack *stack = init();
  12.  
  13.     push(stack, &dado1);
  14.     tmp = pop(stack);
  15.    
  16.     push(stack, &dado1);
  17.     push(stack, &dado3);
  18.     tmp = pop(stack);
  19.  
  20.     push(stack, &dado3);
  21.     push(stack, &dado3);
  22.     push(stack, &dado4);
  23.     push(stack, &dado1);
  24.     tmp = pop(stack);
  25.  
  26.     echo(stack);
  27.  
  28.     deInit(stack);
  29.  
  30.     return 0;
  31. }
  32.  
  33. Stack *init()
  34. {
  35.     Stack *stack = malloc(sizeof(Stack));
  36.    
  37.     stack->headNode = NULL;
  38.     stack->size = 0;
  39.  
  40.     printf("Init Stack \n");
  41.     return stack;
  42. }
  43.  
  44. void push(Stack *stack, int *pData)
  45. {
  46.     Node *node = malloc(sizeof(Node));
  47.    
  48.     node->pData = pData;
  49.     node->pNext = stack->headNode;
  50.    
  51.     stack->headNode = node;
  52.     stack->size += 1;
  53. }
  54.  
  55. int pop(Stack *stack)
  56. {
  57.     int popNode;
  58.     Node *node = stack->headNode->pNext;
  59.    
  60.     popNode =  *(stack->headNode->pData);
  61.    
  62.     free(stack->headNode);
  63.    
  64.     stack->headNode = node;
  65.     stack->size -= 1;
  66.  
  67.     return popNode;
  68. }
  69.  
  70. void echo(Stack *stack)
  71. {
  72.     Node *node;
  73.     printf("Head ->" );
  74.     while(NULL != stack->headNode)
  75.     {
  76.         node = stack->headNode;            
  77.         stack->headNode = stack->headNode->pNext;
  78.         printf("\t %d\n", *(node->pData));
  79.     }  
  80. }
  81.  
  82. int getSize(Stack *stack)
  83. {
  84.     printf("%d\n", stack->size);
  85.     return stack->size;
  86. }
  87.  
  88. void deInit(Stack *stack)
  89. {
  90.     Node *node;
  91.    
  92.     while(NULL != stack->headNode)
  93.     {
  94.         node = stack->headNode;            
  95.         stack->headNode = stack->headNode->pNext;
  96.         free(node);
  97.         node = NULL;
  98.     }  
  99.  
  100.     free(stack);
  101.     stack = NULL;
  102.     printf("DeInit Stack\n");
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement