-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackExample.java
More file actions
61 lines (50 loc) · 1.39 KB
/
StackExample.java
File metadata and controls
61 lines (50 loc) · 1.39 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.codechef;
import java.util.ArrayList;
class Stack<T>{
private ArrayList<T> stack;
public Stack() {
stack = new ArrayList<T>();
}
// add an item to the top of the stack
public void push(T item) {
stack.add(item);
}
//remove and the top item from the stack
public T pop() {
if(isEmpty()) {
throw new IllegalStateException("stack is empty");
}
return stack.remove(stack.size()-1);
}
//Look at the top item without removing it.
public T peek() {
if(isEmpty()) {
throw new IllegalStateException("stack is empty");
}
return stack.get(stack.size()-1);
}
//check if the stack is empty
public boolean isEmpty() {
return stack.isEmpty();
}
//get the size of stack
public int size() {
return stack.size();
}
}
public class StackExample {
public static void main(String[] args) {
Stack<String> bookStack = new Stack<String>();
// Add books to the stack
bookStack.push("Book 1");
bookStack.push("Book 2");
bookStack.push("Book 3");
System.out.println("Stack size: " + bookStack.size());
System.out.println("Top book: " + bookStack.peek());
// Remove the top book
String removedBook = bookStack.pop();
System.out.println("Removed book: " + removedBook);
System.out.println("New stack size: " + bookStack.size());
System.out.println("New top book: " + bookStack.peek());
}
}