#include <stdio.h> #include <stdlib.h> struct stack { int size; int top; int *arr; }; int isempty(struct stack *ptr) { if (ptr->top == -1) { return 1; } else { return 0; } } int isfull(struct stack *ptr) { if (ptr->top == ptr->size - 1) { return 1; } else { return 0; } } void push(struct stack *ptr, int val) { if (isfull(ptr)) { printf("stack is overflow !canot push %d to the stack\n", val); // return -1; } else { ptr->top++; ptr->arr[ptr->top] = val; } } int pop(struct stack *ptr) { if (isempty(ptr)) { printf("stack is overflow !canot pop from the stack\n"); return -1; } else { int val = ptr->arr[ptr->top]; ptr->top--; return val; } } void printStack(struct stack *ptr) { printf("Stack: "); for (int i = ptr->top; i >= 0; i--) { printf("%d ", ptr->arr[i]); } printf("\n"); } int main() { // Allocate memory for the struct stack struct stack *s = (struct stack *)malloc(sizeof(struct stack)); s->size = 5; s->top = -1; s->arr = (int *)malloc(s->size * sizeof(int)); printf("before push, full %d\n", isfull(s)); printf("before push, empty %d\n", isempty(s)); push(s, 1); push(s, 2); push(s, 3); push(s, 4); push(s, 5); printf("after push, full %d\n", isfull(s)); printf("after push, empty %d\n", isempty(s)); printStack(s); printf("popped %d from the stack\n", pop(s)); // printf("popped %d from the stack\n", pop(s)); // printf("popped %d from the stack\n", pop(s)); // printf("popped %d from the stack\n", pop(s)); // printf("popped %d from the stack\n", pop(s)); printStack(s); return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter