X687: LinkedStackFindBase

For the question below, assume the following implementation of LinkedStack:

public class LinkedStack<T> implements StackInterface<T> {
    private Node<T> topNode;
    private int numberOfEntries;

    public LinkedStack() {
        this.topNode = null;
        numberOfEntries = 0;
    }// end default constructor

    @Override
    public void push(T newEntry) {
        topNode = new Node<T>(newEntry, topNode);
        numberOfEntries++;
    }


    @Override
    public T peek() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        else {
            return (T)topNode.getData();
        }
    }// end peek


    @Override
    public T pop() {
        T top = peek();
        topNode = topNode.getNext();
        numberOfEntries--;
        return top;
    }


    @Override
    public boolean isEmpty() {
        return topNode == null;
    }


    @Override
    public void clear() {
        topNode = null;
    }
} // end LinkedStack

    public class Node<E> {
        private E data; // Entry in bag
        private Node<E> next; // Link to next node

        public Node(E dataPortion) {
            this(dataPortion, null);
        } // end constructor


        public Node(E dataPortion, Node<E> nextNode) {
            data = dataPortion;
            next = nextNode;
        } // end constructor


        public E getData() {
            if (data != null) {
                return data;
            }
            return null;
        }


        public Node<E> getNext() {
            return next;
        }


        public void setNext(Node<E> newNext) {
            next = newNext;
        }
    } // end Node

Below, you'll see the start of a method to find the bottom item in a stack.

So if you had the following code:

LinkedStack<Integer> lstack = new LinkedStack<Integer>();
lstack.push(5);
lstack.push(10);
lstack.push(15);

running lstack.getBaseOfStack() would return 5.

If the stack is empty this code should return null!

Add in the code to finish this method.

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.