create a stack in c
include
include
// Structure to represent a stack struct Stack { int top; unsigned capacity; int* array; };
// Function to create a stack of given capacity struct Stack createStack(unsigned capacity) { struct Stack stack = (struct Stack)malloc(sizeof(struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int)malloc(stack->capacity * sizeof(int)); return stack; }
// Function to check if the stack is full int isFull(struct Stack* stack) { return stack->top == stack->capacity - 1; }
// Function to check if the stack is empty int isEmpty(struct Stack* stack) { return stack->top == -1; }
// Function to push an element to the stack void push(struct Stack* stack, int item) { if (isFull(stack)) { printf("Stack Overflow\n"); return; } stack->array[++stack->top] = item; printf("%d pushed to stack\n", item); }
// Function to pop an element from the stack int pop(struct Stack* stack) { if (isEmpty(stack)) { printf("Stack Underflow\n"); return -1; } return stack->array[stack->top--]; }
// Function to get the top element of the stack int peek(struct Stack* stack) { if (isEmpty(stack)) { printf("Stack is empty\n"); return -1; } return stack->array[stack->top]; }
// Driver program to test above functions int main() { struct Stack* stack = createStack(5);
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("%d popped from stack\n", pop(stack));
printf("Top element is %d\n", peek(stack));
return 0;
}