fork download
  1. #include<stdio.h>
  2. #include<assert.h>
  3. #include<stdlib.h>
  4.  
  5. typedef int Elem;
  6.  
  7. struct Stack {
  8. int Max;
  9. int SP;
  10. Elem* SS;
  11. };
  12.  
  13. void stack_init(struct Stack *s, int size) {
  14. s->SP = 0;
  15. s->Max = size;
  16. s->SS = (Elem*)malloc(sizeof(Elem)*size);
  17. assert(s->SS!=NULL);
  18. }
  19.  
  20. void stack_push(struct Stack *s, Elem e) {
  21. if (s->SP >= s->Max) {
  22. Elem *temp = (Elem*)malloc(sizeof(Elem)*2*s->Max);
  23. assert(temp!=NULL);
  24. int i;
  25. for(i=0; i<s->Max; i++) {
  26. temp[i] = s->SS[i];
  27. }
  28. free(s->SS);
  29. s->SS = temp;
  30. s->Max*=2;
  31. }
  32. s->SS[s->SP++] = e;
  33. }
  34.  
  35. Elem stack_pop(struct Stack *s) {
  36. assert(s->SP>0);
  37. return s->SS[--s->SP];
  38. }
  39.  
  40.  
  41.  
  42. int main()
  43. {
  44. struct Stack s1;
  45. stack_init(&s1, 2);
  46. stack_push(&s1, 5);
  47. stack_push(&s1, 4);
  48. stack_push(&s1, 3);
  49. stack_push(&s1, 2);
  50. stack_push(&s1, 1);
  51. printf("%d\n", stack_pop(&s1));
  52. printf("%d\n", stack_pop(&s1));
  53. printf("%d\n", stack_pop(&s1));
  54. printf("%d\n", stack_pop(&s1));
  55. printf("%d\n", stack_pop(&s1));
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0s 1852KB
stdin
Standard input is empty
stdout
1
2
3
4
5