title: How to code a peek method for Linked List
body: <p>I am creating a linked list implementation for a stack. I've got the pop and push method done, but I can't seem to get the peek methods right. The code I have now in there, returns the memory address I think.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public class LinkedStack&lt;T&gt; implements StackADT&lt;T&gt; {
  
  private int count;
  private LinearNode&lt;T&gt; contents;
  
  public LinkedStack() {
      count = 0;
      contents = null;
  }
  
  @Override
  public void push(T element) {
      LinearNode&lt;T&gt; top = new LinearNode&lt;T&gt;(element);
  
      if (contents == null) {
          contents = top;
      } else {
          LinearNode&lt;T&gt; current = contents;
  
          while (current.getNext() != null) {
              current = current.getNext();
          }
          current.setNext(top);
      }
      count++;
  }
  
  @SuppressWarnings("unchecked")
  @Override
  public T pop() {
      T item = (T) contents;
      contents = contents.getNext();
      count--;
      return item;
  }
  
  @SuppressWarnings("unchecked")
  @Override
  public T peek() throws NoSuchOperationException {
  
      T top = (T) contents;
      if(top == null){
          throw new NoSuchOperationException();
      }
      return top;
  }
  
  @Override
  public boolean isEmpty() {
      // TODO Auto-generated method stub
      return false;
  }
  
  @Override
  public int size() {
      return count;
  }
  }
  </code></pre>
  
  <p>This is what it outputs when I call the peek method. I used my push method to add an object, and I tested it with the size method. It showed that I added an element. Then I called my pop method and displayed the size again to make sure that worked.</p>
  
  <p>This is my output of the peek method:</p>
  
  <p>LinearNode@33f42b49</p>
  
  <p>Here is my LinearNode class:</p>
  
  <pre><code>public class LinearNode&lt;T&gt; {
  private T element;
  private LinearNode&lt;T&gt; next;
  
  public LinearNode() {
      this.element = null;
      this.next = null;
  }
  public LinearNode(T element) {
      this.element = element;
      this.next = null;
  }
  public T getElement() {
      return element;
  }
  public void setElement(T _element) {
      this.element = _element;
  }
  public LinearNode&lt;T&gt; getNext() {
      return next;
  }
  public void setNext(LinearNode&lt;T&gt; next) {
      this.next = next;
  }
  </code></pre>
  
  <p>}</p>