Untitled

 avatar
unknown
plain_text
23 days ago
1.6 kB
5
Indexable
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a stack node
struct Node {
    int data;
    struct Node* next;
};

// Function to push an element onto the stack
void push(struct Node** top, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = *top;
    *top = newNode;
    printf("%d pushed to stack\n", data);
}

// Function to pop an element from the stack
int pop(struct Node** top) {
    if (*top == NULL) {
        printf("Stack underflow\n");
        return -1; // Return -1 to indicate stack is empty
    }
    struct Node* temp = *top;
    int poppedData = temp->data;
    *top = (*top)->next;
    free(temp);
    return poppedData;
}

// Function to print the stack
void printStack(struct Node* top) {
    if (top == NULL) {
        printf("Stack is empty\n");
        return;
    }
    printf("Stack elements: ");
    while (top != NULL) {
        printf("%d ", top->data);
        top = top->next;
    }
    printf("\n");
}

// Main function to demonstrate stack operations
int main() {
    struct Node* stack = NULL; // Initialize the stack as empty

    push(&stack, 10);
    push(&stack, 20);
    push(&stack, 30);
    
    printStack(stack);
    
    printf("%d popped from stack\n", pop(&stack));
    printStack(stack);
    
    printf("%d popped from stack\n", pop(&stack));
    printStack(stack);
    
    printf("%d popped from stack\n", pop(&stack));
    printStack(stack);
    
    // Attempt to pop from an empty stack
    pop(&stack);
    
    return 0;
}
Editor is loading...
Leave a Comment