I am currently preparing for my exam and I am trying to implement some abstract data types with linked lists as preparation for the exam. I found an older exam from my prof. and he wants us to implement an ADT stack with an inner class ListElement
.
He has given us the interface, so it doesn't need to be implemented. He wants us to use his given methods, so we are not allowed to change them. This is what I did and I am not sure whether it is right or wrong.
public class Stack<T> implements ADTStack<T> {
private ListElement<T> firstElement;
int size = 0;
public Stack() {
firstElement = null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void push(T element) {
if (empty()) {
firstElement = new ListElement(element);
size++;
}
else {
firstElement.nextElement = firstElement;
firstElement = new ListElement(element);
size++;
}
}
@Override
public void pop() {
if (empty()) {
throw new RuntimeException("stack is empty");
}
else {
T element = top();
firstElement = firstElement.nextElement;
size--;
}
}
@Override
public T top() {
if (empty()) {
return null;
}
else {
return firstElement.element;
}
}
@Override
public boolean empty() {
return (firstElement == null);
}
@Override
public int size() {
return size;
}
public class ListElement<T> {
private T element = null;
private ListElement<T> nextElement = null;
public ListElement(T element) {
this.element = element;
}
public T getElement() {
return element;
}
public ListElement<T> getNextElement() {
return nextElement;
}
public void setNextElement(ListElement<T> element) {
this.nextElement = nextElement;
}
}
}