forked from s-u-m-i-t-0/JavaDataStructuresAndAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava_stack_dataStructure.java
More file actions
29 lines (23 loc) · 985 Bytes
/
java_stack_dataStructure.java
File metadata and controls
29 lines (23 loc) · 985 Bytes
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
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// Creating a Stack
Stack<String> stackOfCards = new Stack<>();
// Pushing new items to the Stack
stackOfCards.push("Jack");
stackOfCards.push("Queen");
stackOfCards.push("King");
stackOfCards.push("Ace");
System.out.println("Stack => " + stackOfCards);
System.out.println();
// Popping items from the Stack
String cardAtTop = stackOfCards.pop(); // Throws EmptyStackException if the stack is empty
System.out.println("Stack.pop() => " + cardAtTop);
System.out.println("Current Stack => " + stackOfCards);
System.out.println();
// Get the item at the top of the stack without removing it
cardAtTop = stackOfCards.peek();
System.out.println("Stack.peek() => " + cardAtTop);
System.out.println("Current Stack => " + stackOfCards);
}
}