Sunday, May 12, 2019

How do you implement stack in java

Problem statement:
Stack data structure implementation in java.
  1. public class Stack {
  2.     static final int max = 15;
  3.     int top;
  4.     int a[] = new int[max];
  5.     boolean push(int x) {
  6.         if (top >= (max - 1)) {
  7.             System.out.println("stack overflow");
  8.             return false;
  9.         } else {
  10.             a[++top] = x;
  11.             System.out.println(x + " pushed into stack");
  12.             return true;
  13.         }
  14.     }
  15.     int pop() {
  16.         if (top < 0) {
  17.             System.out.println("stack underflow");
  18.             return 0;
  19.         } else {

  20.             int x = a[top--];
  21.             return x;
  22.         }
  23.     }
  24.     int size() {
  25.         return top + 1;
  26.     }
  27.     boolean isEmpty() {
  28.         return top == -1;
  29.     }
  30.     boolean isFull() {
  31.         return (top == (max - 1));
  32.     }
  33.     int peak() {
  34.         if (!isEmpty())
  35.             return a[top];
  36.         else return -1;
  37.     }
  38.     Stack() {
  39.         top = -1;
  40.     }
  41. }
  42. class MainExecution {
  43.     public static void main(String[] args) {
  44.         Stack s = new Stack();
  45.         s.push(10);
  46.         s.push(20);
  47.         s.push(30);
  48.         System.out.println("size: " + s.size());
  49.         s.push(25);
  50.         System.out.println("new size: " + s.size());
  51.         System.out.println(s.pop() + " popped from stack");
  52.         System.out.println("top element is peak: "+s.peak());
  53.     }
  54. }
Output:
10 pushed into stack
20 pushed into stack
30 pushed into stack
size: 3
25 pushed into stack
new size: 4
25 popped from stack
top element peak: 30

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...