-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack Operations in Java
More file actions
36 lines (28 loc) · 1.09 KB
/
Stack Operations in Java
File metadata and controls
36 lines (28 loc) · 1.09 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
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// Creating a Stack
Stack<Integer> stack = new Stack<>();
// Pushing elements onto the stack
stack.push(5);
stack.push(15);
stack.push(25);
stack.push(35);
// Displaying the stack
System.out.println("Stack: " + stack);
// Peeking at the top element of the stack
int topElement = stack.peek();
System.out.println("Top element: " + topElement);
// Popping elements from the stack
int poppedElement = stack.pop();
System.out.println("Popped element: " + poppedElement);
// Displaying the stack after popping an element
System.out.println("Stack after pop: " + stack);
// Checking if the stack is empty
boolean isEmpty = stack.isEmpty();
System.out.println("Is stack empty? " + isEmpty);
// Searching for an element in the stack
int position = stack.search(15);
System.out.println("Position of 15 (1-based): " + position);
}
}