Array Stack

Lab C Intermediate 20 points

Implement a stack with an array and a top index. Commands: push X, pop (print the value or empty), peek, size.

Input

n, then n commands.

Output

Output of pop/peek/size.

Example

Input

6
push 1
push 2
peek
pop
size
pop

Output

2
2
1
1
Sample input available Sample output available
Editor
C

Hints

top is the number of items; the top item is stack[top - 1].

Solution explanation

A stack is Last-In-First-Out: push and pop both happen at the top.

Show solution
#include <stdio.h>
#include <string.h>

int stack[100];
int top = 0;

int main() {
    int n, x;
    char cmd[10];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%s", cmd);
        if (strcmp(cmd, "push") == 0) {
            scanf("%d", &x);
            stack[top] = x;
            top++;
        } else if (strcmp(cmd, "pop") == 0) {
            if (top == 0) printf("empty\n");
            else {
                top--;
                printf("%d\n", stack[top]);
            }
        } else if (strcmp(cmd, "peek") == 0) {
            if (top == 0) printf("empty\n");
            else printf("%d\n", stack[top - 1]);
        } else {
            printf("%d\n", top);
        }
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD