AlgoDocs

Stack Implementation Using Array

Implementing stack operations using a Array

Implementation

Initialize Stack

  • Create a structure stack that holds an integer array (arr[MAX]) and an integer top that tracks the top of the stack.
  • Set the top to -1, which indicates that the stack is initially empty.

Check if Stack is Full

  • If top equals MAX - 1 (the last index of the array), the stack is full.
  • Return TRUE if full, otherwise return FALSE.

Check if Stack is Empty

  • If top equals -1, the stack is empty.
  • Return TRUE if empty, otherwise return FALSE.

Push Operation

  • First, check if the stack is full by calling the isFull() function.
  • If the stack is full, print Stack Overflow.
  • If not, increment the top by 1 and insert the new element at arr[top].

Pop Operation

  • First, check if the stack is empty by calling the isEmpty() function.
  • If the stack is empty, print Stack Underflow and return -1.
  • If not, return the value at arr[top] and then decrement top by 1.

Coding Implementation

#include <stdio.h>
#define MAX 100

int stack[MAX];
int top = -1;

int isFull() {
    return top == MAX - 1;
}

int isEmpty() {
    return top == -1;
}

void push(int value) {
    if (isFull()) {
        printf("Stack Overflow\n");
    } else {
        top++;
        stack[top] = value;
    }
}

int pop() {
    if (isEmpty()) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        return stack[top--];
    }
}
#include <iostream>
#define MAX 100

int stack[MAX];
int top = -1;

bool isFull() {
    return top == MAX - 1;
}

bool isEmpty() {
    return top == -1;
}

void push(int value) {
    if (isFull()) {
        std::cout << "Stack Overflow" << std::endl;
    } else {
        top++;
        stack[top] = value;
    }
}

int pop() {
    if (isEmpty()) {
        std::cout << "Stack Underflow" << std::endl;
        return -1;
    } else {
        return stack[top--];
    }
}
MAX = 100
stack = []

def is_full():
    return len(stack) == MAX

def is_empty():
    return len(stack) == 0

def push(value):
    if is_full():
        print("Stack Overflow")
    else:
        stack.append(value)

def pop():
    if is_empty():
        print("Stack Underflow")
        return -1
    else:
        return stack.pop()
const MAX = 100;
let stack = [];

function isFull() {
  return stack.length === MAX;
}

function isEmpty() {
  return stack.length === 0;
}

function push(value) {
  if (isFull()) {
    console.log("Stack Overflow");
  } else {
    stack.push(value);
  }
}

function pop() {
  if (isEmpty()) {
    console.log("Stack Underflow");
    return -1;
  } else {
    return stack.pop();
  }
}

Comparison of Stack Implementation Using Array and Linked List

Comparison of Stack Implementation Using Array and Linked List

How is this guide?