Stack implementation using nodes Purpose

Implement a Stack with push, pop, and peek methods.


The push method should add an element to the "top" of the Stack.
The pop method should remove the "top" element from the Stack.
The peek method should return the "top" element of the Stack.


Approach

I decided to create a Node class to represent the elements in a Stack. The Node class would have a data field
and a previous field that would reference another Node. By having this previous field one can "chain" Nodes together.

For my Stack class, I decided to set the head (i.e. the Node at the "top" of the Stack) value to null on initialization.
I also decided to throw Exceptions when calling peek or pop for an empty Stack (i.e. when the head value is null).

I could see an argument to not throw Exceptions but rather return null for peek or nothing for pop (since it's void).
However, null is a valid value for an Object, and since a Stack is made up of Objects, I think returning
null when calling peek for an empty Stack could be confusing.

public class Node&lt;T&gt; {
  T data;
  Node&lt;T&gt; previous;

  public Node(T data, Node&lt;T&gt; previous) {
    this.data = data;
    this.previous = previous;
  }

  public T getData() {
    return data;
  }

  public Node&lt;T&gt; getPrevious() {
    return previous;
  }
}

public class Stack&lt;T&gt; {
  Node&lt;T&gt; head = null;

  public Stack() {
  }

  public T peek() {
    if (this.head == null) {
      throw new RuntimeException("Unable to peek element for an empty stack");
    }

    return this.head.getData();
  }

  public void push(T data) {
    this.head = new Node&lt;&gt;(data, this.head);
  }

  public void pop() {
    if (this.head == null) {
      throw new RuntimeException("Unable to remove element from an empty stack");
    }

    this.head = this.head.getPrevious();
  }
Don't throw RuntimeException: they are not specific, and hence difficult to catch.  (Otherwise, you might as well drop the null checks and let it fail naturally with NullPointerException, which is also a kind of RuntimeException.) You should make your own exception subclass, or use java.util.NoSuchElementException.

It would also make sense to support an isEmpty() method, to give the user a fair chance to avoid the exception.

Two spaces per level of indentation is too narrow and unconventional for my taste, and could also encourage excessive nesting.  Four or eight spaces would be acceptable.