Linked Stack Implementation
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Stack {
struct Node* top;
};
void initialize(struct Stack* stack) {
stack->top = NULL;
}
int isEmpty(struct Stack* stack) {
return (stack->top == NULL);
}
void push(struct Stack* stack, int element) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed. Cannot push element onto the stack.\\n");
return;
}
newNode->data = element;
newNode->next = stack->top;
stack->top = newNode;
printf("Pushed: %d\\n", element);
}
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty. Cannot pop element.\\n");
return -1;
}
struct Node* temp = stack->top;
int poppedElement = temp->data;
stack->top = temp->next;
free(temp);
printf("Popped: %d\\n", poppedElement);
return poppedElement;
}
void display(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\\n");
} else {
struct Node* current = stack->top;
printf("Stack elements: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\\n");
}
}
int main() {
struct Stack intStack;
initialize(&intStack);
push(&intStack, 10);
push(&intStack, 20);
push(&intStack, 30);
display(&intStack);
pop(&intStack);
display(&intStack);
push(&intStack, 40);
push(&intStack, 50);
push(&intStack, 60);
display(&intStack);
pop(&intStack);
display(&intStack);
return 0;
}