Java Implement StackInterface using a ListInterface object as the underlying dat
ID: 3581321 • Letter: J
Question
Java
Implement StackInterface using a ListInterface object as the underlying data structure.
The class and some methods are implemented below.
For this question, implement the three missing methods: pop, push, and peek.
public class StackAsList<T> implements StackInterface<T> {
private ListInterface<T> list;
public StackAsList () {
list = new AList<T>();
}
public void push(T newEntry) {
// IMPLEMENT THIS METHOD
}
public T pop() {
// IMPLEMENT THIS METHOD
}
public T peek() {
// IMPLEMENT THIS METHOD
}
public boolean isEmpty() {
return list.isEmpty();
}
public void clear() {
list.clear();
}
}
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
public class StackAsList<T> implements StackInterface<T> {
private ListInterface<T> list;
public StackAsList () {
list = new AList<T>();
}
public void push(T newEntry) {
list.add(newEntry);
}
public T pop() {
if(isEmpty())
return null;
else{
T item = list.get(list.size()-1);
list.remove(list.size()-1);
return item;
}
}
public T peek() {
if(isEmpty())
return null;
else{
return list.get(list.size()-1);
}
}
public boolean isEmpty() {
return list.isEmpty();
}
public void clear() {
list.clear();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.