In my code I was trying to do the stack operations like push,pop and peek using methods in java with arraylist i have implemented the code with the stack logic which has complexity o(1),but when i run my code i get an error that the pop,push ,and peek methods are undefined in the stack class if someone could help me where i went wrong it would be a great help.Thank you.
My code :
import java.util.*;
public class StackClass {
class Stack{
ArrayList<Integer> list = new ArrayList<>();
public static boolean isEmpty(){
return list.size() == 0;
}
}
//push
public static void push(int data){
list.add(data);
}
//pop
public static int pop(){
if(isEmpty()){
return -1;
}
int top = list.get(list.size() - 1);
list.remove(list.size() - 1);
return top;
}
//peek
public static int peek(){
if(isEmpty()){
return -1;
}
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);
s.push(4);
while(!s.isEmpty()){
System.out.println(s.peek());
s.pop();
}
}
}
Im getting the error like this:
The method push(int) is undefined for the type StackClass.Stack
The method push(int) is undefined for the type StackClass.Stack
The method push(int) is undefined for the type StackClass.Stack
The method push(int) is undefined for the type StackClass.Stack
The method peek() is undefined for the type StackClass.Stack
The method pop() is undefined for the type StackClass.Stack
Jyothiradithya G KIT_2_7567 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2