javatechie

Custom Stack Implementation

Sep 21st, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. package com.javatechie.ds;
  2.  
  3. public class Stack {
  4.  
  5.     int[] stack = new int[5];
  6.     int top = 0;
  7.  
  8.     public void push(int element) {
  9.         stack[top] = element;
  10.         top++;
  11.     }
  12.  
  13.     public int pop() {
  14.         top--;
  15.         int element = stack[top];
  16.         stack[top] = 0;
  17.         return element;
  18.     }
  19.  
  20.     public int peek() {
  21.         return stack[top - 1];
  22.     }
  23.  
  24.     public int size() {
  25.         return top;
  26.     }
  27.  
  28.     public boolean isEmpty() {
  29.         return top == 0 ? true : false;
  30.     }
  31.  
  32.     public static void main(String[] args) {
  33.         Stack stack = new Stack();
  34.         stack.push(12);
  35.         stack.push(5);
  36.         stack.push(7);
  37.         stack.push(8);
  38.         stack.push(4);
  39.  
  40.         System.out.println("Element : " + stack.pop());
  41.         System.out.println("peek() : " + stack.peek());
  42.         System.out.println("Size : " + stack.size());
  43.         System.out.println("isEmpty : " + stack.isEmpty());
  44.     }
  45. }
Add Comment
Please, Sign In to add comment