Back
Close

Stack – Data Structure

Damith
7,735 views

Introduction

Stack is a LIFO (Last in first out) data structure.

Operations

  1. pop() – adds an element in the stack.
  2. push() – removes an element from the stack.
  3. peek() – get the top element without removing it.
  4. isEmpty() – checks whether stack is empty or not.
  5. isFull() – checks whether stack is full or not.

Implementation

There are 2 ways to implement a stack.

  1. Array-based Stack
  2. Linked List based Stack

Array-based Stack

class Stack {
private int top;
private int capacity;
private int[] array;
public Stack(int capacity){
this.capacity = capacity;
this.array = new int[capacity];
this.top = -1;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Pros:-

  • Easier to use.
  • Less memory allocation because no need to track the next node.

Cons:-

  • Fixed size – can not increase or decrease the array.

Link List based Stack

class StackNode {
int data;
StackNode next;
}
class Stack {
private StackNode root;
public boolean isEmpty(){
return this.root == null;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Pros:-

  • Easily increase or decrease the Stack size.

Cons:-

  • Requires extra memory to keep details about next node.

Original post : - http://mydevgeek.com/stack-data-strurcture/

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants