How to code a peek method for Linked List

Brock picture Brock · Oct 6, 2011 · Viewed 12.2k times · Source

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.

Here is my code:

public class LinkedStack<T> implements StackADT<T> {

private int count;
private LinearNode<T> contents;

public LinkedStack() {
    count = 0;
    contents = null;
}

@Override
public void push(T element) {
    LinearNode<T> top = new LinearNode<T>(element);

    if (contents == null) {
        contents = top;
    } else {
        LinearNode<T> 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;
}
}

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.

This is my output of the peek method:

LinearNode@33f42b49

Here is my LinearNode class:

public class LinearNode<T> {
private T element;
private LinearNode<T> 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<T> getNext() {
    return next;
}
public void setNext(LinearNode<T> next) {
    this.next = next;
}

}

Answer

Jim Kiley picture Jim Kiley · Oct 6, 2011

Sounds like the LinearNode class needs a toString() method.