Thursday, May 26, 2016

MyStack (LIFO) : Stack implementation with Array and Generics

MyStack.java:

package com.lnn.ds.stack;

import java.util.Objects;

public class MyStack<T> {
      private T[] data;
      private int size = -1;
      private int capacity;

      @SuppressWarnings("unchecked")
      public MyStack(int capacity) {
            this.capacity = capacity;
            this.data = (T[]) new Object[capacity];
      }

      public boolean isFull() {
            return (size + 1 == capacity);
      }

      public boolean isEmpty() {
            return (size == -1);
      }

      public T pop() {
            if (!isEmpty()) {
                  return data[size--];
            }
            return null;
      }

      public boolean push(T element) {
            if (!isFull()) {
                  data[++size] = element;
                  return true;
            }
            return false;
      }

      public boolean search(T element) {
            for (int i = 0; i <= size; i++) {
                  if (Objects.equals(data[i], element)) {
                        return true;
                  }
            }
            return false;
      }

      public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("[");
            for (int i = 0; i <= size; i++) {
                  builder.append(data[i]);
                  if (i < size) {
                        builder.append(", ");
                  }
            }
            builder.append("]");
            return builder.toString();
      }
}

MyStackTest.java:

package com.lnn.ds.stack;

public class MyStackTest {
      public static void main(String[] args) {
            MyStack<Integer> stack = new MyStack<Integer>(10);
            for (int i = 0; i < 10; i++) {
                  stack.push(i);
            }
            for (int i = 0; i < 10; i++) {
                  System.out.println(stack);
                  stack.pop();
            }
      }
}


No comments:

Post a Comment