Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.3 kB
2
Indexable
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 10

struct Stack {
    int items[MAX_SIZE];
    int top;
};

void initialize(struct Stack *stack) {
    stack->top = -1;
}

int is_empty(struct Stack *stack) {
    return stack->top == -1;
}

int is_full(struct Stack *stack) {
    return stack->top == MAX_SIZE - 1;
}

void push(struct Stack *stack, int item) {
    if (!is_full(stack)) {
        stack->items[++stack->top] = item;
        printf("Pushed %d onto the stack.\n", item);
    } else {
        printf("Stack is full. Cannot push.\n");
    }
}

void pop(struct Stack *stack) {
    if (!is_empty(stack)) {
        int popped_item = stack->items[stack->top--];
        printf("Popped %d from the stack.\n", popped_item);
    } else {
        printf("Stack is empty. Cannot pop.\n");
    }
}

void peek(struct Stack *stack) {
    if (!is_empty(stack)) {
        printf("Top item: %d\n", stack->items[stack->top]);
    } else {
        printf("Stack is empty. Cannot peek.\n");
    }
}

void display(struct Stack *stack) {
    if (!is_empty(stack)) {
        printf("Stack contents:");
        for (int i = 0; i <= stack->top; i++) {
            printf(" %d", stack->items[i]);
        }
        printf("\n");
    } else {
        printf("Stack is empty.\n");
    }
}

int main() {
    struct Stack stack;
    initialize(&stack);

    while (1) {
        printf("\nStack Menu:\n");
        printf("1. Push\n");
        printf("2. Pop\n");
        printf("3. Peek\n");
        printf("4. Display\n");
        printf("5. Quit\n");

        int choice;
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1: {
                int item;
                printf("Enter item to push onto the stack: ");
                scanf("%d", &item);
                push(&stack, item);
                break;
            }
            case 2:
                pop(&stack);
                break;
            case 3:
                peek(&stack);
                break;
            case 4:
                display(&stack);
                break;
            case 5:
                printf("Exiting the program.\n");
                exit(0);
            default:
                printf("Invalid choice. Please select a valid option.\n");
        }
    }

    return 0;
}