#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Stack;
Stack* createNode(int value) {
Stack* head = (Stack*)malloc(sizeof(Stack));
if (head == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
head->data = value;
head->next = NULL;
return head;
}
Stack* push(Stack* top, int value) {
Stack* temp = createNode(value);
temp->next = top;
return temp;
}
Stack* pop(Stack* top) {
if (top == NULL) {
printf("Stack is Empty\n");
return top;
}
printf("Element popped is %d\n", top->data);
Stack* temp = top;
top = top->next;
free(temp);
return top;
}
void peek(Stack* top) {
if (top == NULL) {
printf("Empty\n");
return;
}
printf("%d\n", top->data);
}
void traverse(Stack* top) {
if (top == NULL) {
printf("Stack is empty\n");
return;
}
printf("Elements in the stack are:\n");
Stack* ptr = top;
while (ptr != NULL) {
printf("%d\n", ptr->data);
ptr = ptr->next;
}
}
int main() {
Stack* top = NULL;
top = push(top, 23);
top = push(top, 24);
top = push(top, 25);
traverse(top);
top = pop(top);
top = pop(top);
peek(top);
traverse(top);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCnR5cGVkZWYgc3RydWN0IE5vZGUgewogICAgaW50IGRhdGE7CiAgICBzdHJ1Y3QgTm9kZSogbmV4dDsKfSBTdGFjazsKClN0YWNrKiBjcmVhdGVOb2RlKGludCB2YWx1ZSkgewogICAgU3RhY2sqIGhlYWQgPSAoU3RhY2sqKW1hbGxvYyhzaXplb2YoU3RhY2spKTsKICAgIGlmIChoZWFkID09IE5VTEwpIHsKICAgICAgICBwcmludGYoIk1lbW9yeSBhbGxvY2F0aW9uIGZhaWxlZFxuIik7CiAgICAgICAgZXhpdCgxKTsKICAgIH0KICAgIGhlYWQtPmRhdGEgPSB2YWx1ZTsKICAgIGhlYWQtPm5leHQgPSBOVUxMOwogICAgcmV0dXJuIGhlYWQ7Cn0KClN0YWNrKiBwdXNoKFN0YWNrKiB0b3AsIGludCB2YWx1ZSkgewogICAgU3RhY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