Skip to content

Instantly share code, notes, and snippets.

@skmangalam
Created December 19, 2017 10:44
Show Gist options
  • Save skmangalam/08692842a07faac4899b86f718dc1dc8 to your computer and use it in GitHub Desktop.
Save skmangalam/08692842a07faac4899b86f718dc1dc8 to your computer and use it in GitHub Desktop.
Implementation Of Stack Using ArrayList
import java.util.ArrayList;
public class ListStack<X> implements Stack<X> {
private ArrayList<X> list;
public ListStack() {
list = new ArrayList<X>();
}
public void push(X item) {
list.add(item);
}
public X pop() {
if(list.size()==0)
throw new IllegalStateException("Stack is empty");
return list.remove(list.size()-1);
}
public boolean contains(X item) {
return list.contains(item);
}
public X access(X item) {
try {
while (true) {
if (item == pop())
return item;
}
}
catch (Exception e){
System.out.println("Item not found on the stack");
return null;
}
}
public int size() {
return list.size();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment