Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // import modules
- #include <stdio.h>
- #include <limits.h>
- #include <stdlib.h>
- // define Stack struct
- struct Stack {
- int* arr;
- int top;
- unsigned length;
- };
- // create stack function
- struct Stack* createStack(unsigned len) {
- // create stack
- struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
- // insert values
- stack->length = len;
- stack->top = -1;
- stack->arr = (int*)malloc(stack->length * sizeof(int));
- // return stack
- return stack;
- }
- // check stack is full
- int isFull(struct Stack* stack) {
- // check full
- return stack->top == stack->length - 1;
- }
- // check stack is empty
- int isEmpty(struct Stack* stack) {
- // check empty
- return stack->top == -1;
- }
- // push item into the stack
- int push(struct Stack* stack, int i) {
- // check stack is full
- if (isFull(stack)) {
- return 0;
- }
- // insert item
- stack->arr[++stack->top] = i;
- // return top index
- return stack->top;
- }
- // pop from stack
- int pop(struct Stack* stack) {
- // check stack is empty
- if (isEmpty(stack)) {
- return 0;
- }
- // return top value
- return stack->arr[stack->top--];
- }
- // main
- int main(void) {
- // create a stack
- struct Stack* stack = createStack(100);
- // push items
- push(stack, 10);
- push(stack, 20);
- push(stack, 30);
- // print length
- printf("length: %d\n", stack->length);
- // pop item
- printf("pop: %d\n", pop(stack));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement