Answer to Question #240340 in C for xyz

Question #240340

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


1
Expert's answer
2021-09-22T00:02:16-0400
#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() {

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS