forked from hecker9901/Shoping-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.java
49 lines (40 loc) · 1.23 KB
/
Stack.java
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
47
48
49
import java.util.LinkedList;
public class CustomStack<T> {
private LinkedList<T> list = new LinkedList<>();
// Push an element onto the stack
public void push(T item) {
list.addFirst(item);
}
// Pop an element from the stack
public T pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return list.removeFirst();
}
// Peek at the top element without removing it
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return list.getFirst();
}
// Check if the stack is empty
public boolean isEmpty() {
return list.isEmpty();
}
// Get the size of the stack
public int size() {
return list.size();
}
public static void main(String[] args) {
CustomStack<Integer> stack = new CustomStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Popped element: " + stack.pop());
System.out.println("Popped element: " + stack.pop());
System.out.println("Top element: " + stack.peek());
System.out.println("Is the stack empty? " + stack.isEmpty());
}
}