Write a menu-driven program to perform the following operations of a stack using a linked list by using suitable user-defined functions for each case.
a) Check if the stack is empty
b) Display the contents of stack
c) Push
d) Pop
#include <stdio.h>
#include <inttypes.h>
#include <malloc.h>
struct list {
int64_t value;
struct list *next;
};
struct stack {
struct list *items;
};
struct list *node(int64_t value, struct list *next) {
struct list *result = malloc(sizeof(struct list));
*result = (struct list) { value, next };
return result;
}
bool stack_empty(struct stack const *s) {
return (s->items == NULL);
}
void stack_display(struct stack *s) {
struct list *list = s->items;
while (list) {
printf("%" PRIn64 "\n", list->value);
list = list->next;
}
}
bool stack_push(struct stack *s, int64_t value) {
s->items = node(value, s->items);
return true;
}
int64_t stack_pop(struct stack *s) {
if (stack_empty(s)) {
return 0;
}
struct list *node = s->items;
s->items = s->items->next;
int64_t tmp = node->value;
free(node);
return tmp;
}
int main() {
}
Comments
Leave a comment