-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack_00.java
More file actions
46 lines (36 loc) · 1.08 KB
/
Copy pathStack_00.java
File metadata and controls
46 lines (36 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Implementing Stack using ArrayList in Java
import java.util.ArrayList;
class Stack{
ArrayList<Integer> stack;
Stack(){
stack=new ArrayList<>();
}
public void push(int val){
stack.add(val);
}
public int pop(){
if(stack.isEmpty()){
System.out.println("Stack is empty!");
return -1; // Return -1 to indicate stack is empty
}
return stack.remove(stack.size() - 1);
}
public int peek(){
if(stack.isEmpty()){
System.out.println("Stack is empty!");
return -1; // Return -1 to indicate stack is empty
}
return stack.get(stack.size() - 1);
}
}
public class Stack_00 {
public static void main(String[] args){
Stack stack=new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Top element: " + stack.peek()); // Output: 30
System.out.println("Popped element: " + stack.pop()); // Output: 30
System.out.println("Top element after pop: " + stack.peek()); // Output: 20
}
}