Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
2.3 kB
8
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

// Node structure for the circular linked list
struct Node {
    int data;
    struct Node* next;
};

// Structure for the circular linked list-based stack
struct Stack {
    struct Node* top;
};

// Function to initialize an empty stack
void initializeStack(struct Stack* stack) {
    stack->top = NULL;
}

// Function to check if the stack is empty
int isEmpty(struct Stack* stack) {
    return (stack->top == NULL);
}

// Function to push a new element onto the stack
void push(struct Stack* stack, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    if (isEmpty(stack)) {
        newNode->next = newNode; // Point to itself to form a circular list
    } else {
        newNode->next = stack->top->next;
        stack->top->next = newNode;
    }
    stack->top = newNode;
}

// Function to pop the top element from the stack
int pop(struct Stack* stack) {
    if (isEmpty(stack)) {
        printf("Error: Stack underflow\n");
        return -1; // indicating stack underflow
    }

    int poppedData;
    struct Node* temp = stack->top;

    if (temp->next == temp) {
        // If only one element in the circular list
        poppedData = temp->data;
        free(temp);
        stack->top = NULL;
    } else {
        poppedData = temp->data;
        stack->top->next = temp->next;
        stack->top = temp->next;
        free(temp);
    }

    return poppedData;
}

// Function to display the elements of the stack
void display(struct Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty\n");
        return;
    }

    struct Node* current = stack->top->next;
    do {
        printf("%d ", current->data);
        current = current->next;
    } while (current != stack->top->next);

    printf("\n");
}

// Main function to test circular linked list-based stack
int main() {
    struct Stack stack;
    initializeStack(&stack);

    push(&stack, 10);
    push(&stack, 20);
    push(&stack, 30);

    printf("Stack elements: ");
    display(&stack);

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

    printf("Stack elements after pop: ");
    display(&stack);

    return 0;
}

/*
Stack elements: 30 20 10 
Popped element: 30
Stack elements after pop: 20 10
*/
Leave a Comment