Thursday, May 26, 2016

MyStack (LIFO) : Implemented with Generics

MyStack.java:

package com.lnn.ds.stack;

import java.util.Objects;

public class MyStack<T> {
      private static class Node<T> {
            private Node<T> prev;
            private T data;

            public Node(T data) {
                  this.data = data;
            }

            public T getData() {
                  return data;
            }

            public Node<T> getPrev() {
                  return prev;
            }

            public void setPrev(Node<T> prev) {
                  this.prev = prev;
            }

            public String toString() {
                  return String.valueOf(getData());
            }
      }

      private Node<T> tail;

      public boolean isEmpty() {
            return (tail == null);
      }

      public boolean pop() {
            if (tail != null) {
                  Node<T> tmp = tail.getPrev();
                  setTail(tmp);
                  return true;
            }
            return false;
      }

      public void push(T data) {
            Node<T> next = new Node<T>(data);
            next.setPrev(tail);
            setTail(next);
      }

      public boolean search(T data) {
            Node<T> tmp = tail;
            while (tmp != null) {
                  if (Objects.equals(tmp.getData(), data)) {
                        return true;
                  }
                  tmp = tmp.getPrev();
            }
            return false;
      }

      private void setTail(Node<T> tail) {
            this.tail = tail;
      }

      public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("[");
            Node<T> tmp = tail;
            while (tmp != null) {
                  builder.append(tmp.getData());
                  tmp = tmp.getPrev();
                  if (tmp != null) {
                        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>();
            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