Sunday, 5 October 2025

Stack 6


7a
#include 
#include 

#define MAX_SIZE 5

int stack[MAX_SIZE];
int top = -1;

int isEmpty() {
    return top == -1;
}

int isFull() {
    return top == MAX_SIZE - 1;
}

void push(int data) {
    if (isFull()) {
        printf("Stack Full.\n");
        return;
    }
    stack[++top] = data;
}

int pop() {
    if (isEmpty()) {
        printf("Stack Empty.\n");
        return -1;
    }
    return stack[top--];
}

int peek() {
    if (isEmpty()) {
        printf("Stack Empty.\n");
        return -1;
    }
    return stack[top];
}

int main() {
    push(10);
    push(20);
    push(30);
    push(40);
    push(50);

    if (isFull()) printf("Is Full.\n");

    push(60);

    printf("Top: %d\n", peek());

    printf("Popped: %d\n", pop());
    printf("Popped: %d\n", pop());

    printf("Top: %d\n", peek());

    if (!isEmpty()) printf("Not Empty.\n");

    return 0;
}

7b
#include 
#include 

struct Node {
    int data;
    struct Node* next;
};

struct Node* top = NULL;

int isEmpty() {
    return top == NULL;
}

void push(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) return;
    newNode->data = data;
    newNode->next = top;
    top = newNode;
}

int pop() {
    if (isEmpty()) {
        printf("Stack Empty.\n");
        return -1;
    }
    struct Node* temp = top;
    int data = temp->data;
    top = top->next;
    free(temp);
    return data;
}

int peek() {
    if (isEmpty()) {
        printf("Stack Empty.\n");
        return -1;
    }
    return top->data;
}

int main() {
    push(100);
    push(200);
    push(300);

    printf("Top: %d\n", peek());

    printf("Popped: %d\n", pop());
    printf("Popped: %d\n", pop());

    printf("Top: %d\n", peek());

    if (!isEmpty()) printf("Not Empty.\n");

    printf("Popped: %d\n", pop());

    if (isEmpty()) printf("Is Empty.\n");

    return 0;
}

No comments:

Post a Comment