import java.util.ArrayList;
public class StackB {
static class Stack {
static ArrayList<Integer> list = new ArrayList<>();
public static boolean isEmpty() {
return list.size() == 0; // no elements in the stack (my Mistake: without list.size() it wont work, i wrote "list.size" only which let to private access errors)
}
// push - add the data in the stack
public static void push(int data) {
list.add(data);
}
// pop - delete the data from stack
public static int pop() {
int top = list.get(list.size()-1); // gets the last index
list.remove(list.size()-1); // removes it
return top;
}
// peek - view the data from top
public static int peek() {
return list.get(list.size()-1);
}
}
public static void main(String[] args) {
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
while(!s.isEmpty()) {
System.out.println(s.peek());
s.pop();
}
}
}
No comments:
Post a Comment