Uh oh!
There was an error while loading. Please reload this page.
forked from iiitv/algos
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStack.java
More file actions
Latest commit
44 lines (38 loc) · 1.32 KB
/
Copy pathStack.java
File metadata and controls
44 lines (38 loc) · 1.32 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
/*
* Following implementation of Stack uses LinkedList
* The last element of LinkedList is considered as the Top of Stack
* T defines the type of Stack we wish to create
*/
importjava.util.LinkedList;
importjava.util.NoSuchElementException;
publicclassStack<T> {
privateLinkedList<T> stack;
publicStack() { // Constructor to create empty Stack
stack = newLinkedList<>();
}
publicvoidpush(Tdata) { // Add element to Top of Stack
stack.addLast(data);
}
publicTpop() throwsNoSuchElementException { // Remove element from top of Stack
returnstack.removeLast();
}
publicstaticvoidmain(String[] args) {
Stack<Integer> obj = newStack<>();
System.out.println("Putting element in the stack.");
for (inti = 1; i <= 10; i++) {
obj.push(i);
System.out.println("Pushed "+i);
}
System.out.println("\nPoping elements out of stack.");
while(true) { // Remove the elements till stack is empty,
try {
Integercurr_element = obj.pop();
System.out.println("Popped " + curr_element);
}
catch(NoSuchElementExceptionnsee) {
System.out.println("Stack is empty now.");
break;
}
}
}
}