package chapter_3.stack_queue;

import chapter_2.list.Node;

/**
 * Simple Stack implementation
 * 
 * @author Sudharsanan Muralidharan
 * @param <T>
 */
public class CustomStack<T> {
  private Node<T> top = null;
  private int size = 0;

  public CustomStack() {
  }

  /**
   * Pushes data into the stack
   * 
   * @param data
   */
  public void push(T data) {
    if (top == null) {
      top = new Node<T>();
      top.data = data;
      top.next = null;
    } else {
      Node<T> node = new Node<T>();
      node.data = data;
      node.next = top;
      top = node;
    }

    size++;
  }

  /**
   * Pop top of the stack
   */
  public void pop() {
    if (top != null) {
      top = top.next;
      size--;
    }
  }

  /**
   * Returns data in top of the stack
   * 
   * @return top
   */
  public T peek() {
    if (top != null) {
      return top.data;
    }
    return null;
  }

  /**
   * Check if stack is Empty
   * 
   * @return
   */
  public boolean isEmpty() {
    return (size == 0);
  }

  /**
   * Get stack size
   * 
   * @return size
   */
  public int size() {
    return this.size;
  }

  /**
   * @Override toString()
   * Returns the content of the stack
   */
  @Override
  public String toString() {
    Node<T> current = top;
    StringBuilder builder = new StringBuilder();
    builder.append("[");
    while (current != null) {
      builder.append(current.data);
      builder.append((current.next != null) ? " " : "]");
      current = current.next;
    }
    return builder.toString();
  }
}

@@ -25,16 +25,55 @@
 queue;%0A%0A
+import java.util.EmptyStackException;%0A%0A
 import c
@@ -695,33 +695,33 @@
 ) %7B%0A    if (top 
-!
+=
 = null) %7B%0A      
@@ -708,32 +708,76 @@
 op == null) %7B%0A  
+    throw new EmptyStackException();%0A    %7D%0A%0A
     top = top.ne
@@ -788,18 +788,16 @@
     
-  
 size--;%0A
     
@@ -792,22 +792,16 @@
 size--;%0A
-    %7D%0A
   %7D%0A%0A  /
@@ -902,17 +902,17 @@
 if (top 
-!
+=
 = null) 
@@ -923,31 +923,47 @@
     
-return top.data
+throw new EmptyStackException()
 ;%0A    %7D%0A
     
@@ -950,32 +950,33 @@
 eption();%0A    %7D%0A
+%0A
     return null;
@@ -970,20 +970,24 @@
  return 
-null
+top.data
 ;%0A  %7D%0A%0A 
@@ -1239,21 +1239,16 @@
 String()
-%0A   *
  Returns
@@ -1316,24 +1316,78 @@
 oString() %7B%0A
+    if (this.isEmpty()) %7B%0A      return %22%22;%0A    %7D%0A    %0A
     Node%3CT%3E 

Throw exception when top is null