Answer to Question #257235 in C for Jainab

Question #257235

Explain stacks with the help of an example


1
Expert's answer
2021-10-27T00:26:27-0400

A stack is a linear data structure that follows the Last in, First out principle (LIFO)

#include <stdio.h>

const int MAX_SIZE = 64;
int stack[MAX_SIZE];
int top = -1;

int isempty() {
  if (top == -1) { return 1; }
  else { return 0 };
}

int isfull() {
  if (top == MAX_SIZE) { return 1; }
  else { return 0; }
}

int peek() {
  return stack[top];
}

int pop() {
  int data;
  if (!isempty()) {
    data = stack[pop];
    top = top - 1;
    return data;
  } else {
    printf("Couldnt retrieve data, Stack is empty.\n");
  }
}

int push(int data) {
  if (!isfull()) {
    top = top + 1;
    stack[top] = data;
    return 1;
  } else {
    printf("Couldn't not insert data, Stack is full.\n");
    return 0;
  }
}

int main() {
  // push items on to the stack
  push(3);
  push(-3);
  push(32);
  push(23);
  push(6);
  
  printf("Elements: ");
 
  while (!isempty()) {
    int data = pop();
    printf("%d\n", data);
  }
 
  return 0;
}

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