Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. #include"stack_dynamic.h"
  2.  
  3. struct node
  4. {
  5. int item;
  6. struct node *next_node;
  7. };
  8. struct stack
  9. {
  10. Node *top;
  11. };
  12. Stack* create_stack()
  13. {
  14. Stack *stack = (Stack*)malloc(sizeof(Stack));
  15. stack->top = NULL;
  16. return stack;
  17. }
  18. int is_empty(Stack *stack)
  19. {
  20. return (stack->top == NULL);
  21. }
  22. void push(Stack *stack, int item)
  23. {
  24. Node *new_top = (Node*)malloc(sizeof(Node));
  25. new_top->item = item;
  26. new_top->next_node = stack->top;
  27. stack->top = new_top;
  28. }
  29. int pop(Stack *stack)
  30. {
  31. Node *node_aux;
  32. if(is_empty(stack))
  33. {
  34. printf("Empty stack!\n");
  35. return -1;
  36. }
  37. else
  38. {
  39. node_aux = stack->top;
  40. stack->top = node_aux->next_node;
  41. return node_aux->item;
  42. free(node_aux);
  43. }
  44. }
  45. int peek(Stack *stack)
  46. {
  47. if(!is_empty(stack))
  48. return stack->top->item;
  49. else
  50. return -1;
  51. }
  52. int main()
  53. {
  54. int n;
  55. Stack* stk = create_stack();
  56. puts("Digite um numero: ");
  57. scanf("%d", &n);
  58. while(n>0)
  59. {
  60. push(stk, n);
  61. puts("Digite outro numero:");
  62. scanf("%d", &n);
  63. }
  64. printf("O elemento do topo eh %d\n", peek(stk));
  65. while(!is_empty(stk))
  66. printf("%d\n", pop(stk));
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement