forked from NITSkmOS/Algorithms
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
Latest commit
88 lines (78 loc) · 2.19 KB
/
Copy pathStack.java
File metadata and controls
88 lines (78 loc) · 2.19 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
importjava.util.NoSuchElementException;
publicclassStack<Item>{
privateintsize; // size of the Stack
privateNodefirst; // top of Stack
privateclassNode {
privateItemitem;
privateNodenext;
}
/**
* Creates an empty Stack instance
*/
publicStack() {
first = null;
size = 0;
}
/**
* Returns whether the Stack is empty or not.
*
* @return true if the Stack is empty, otherwise false.
*/
publicbooleanisEmpty() {
returnfirst == null;
}
/**
* Returns the amount of times in this Stack.
*
* @return the amount of times in this Stack.
*/
publicintgetSize() {
returnsize;
}
/**
* Add an item to this Stack.
*
* @param item the item to add.
*/
publicvoidpush(Itemitem) {
NodeoldFirst = first;
first = newNode();
first.item = item;
first.next = oldFirst;
size++;
}
/**
* Returns and removes the item on the top of this Stack.
*
* @throws NoSuchElementException if this Stack is empty
*/
publicItempop() throwsNoSuchElementException{
if (isEmpty()) thrownewNoSuchElementException("Stack underflow");
Itemitem = first.item;
first = first.next;
size--;
returnitem;
}
/**
* Returns the top item of the Stack, without removing it.
*
* @return the item on top of this Stack
* @throws NoSuchElementException if this Stack is empty
*/
publicItempeek() throwsNoSuchElementException{
if (isEmpty()) thrownewNoSuchElementException("Stack underflow");
returnfirst.item;
}
/**
* Example usage
*/
publicstaticvoidmain(String[] args) throwsNoSuchElementException {
Stack<String> Stack = newStack<String>();
Stack.push("Hello World");
System.out.println(Stack.peek()); // "Hello World"
Stack.push("I am on the top now");
System.out.println(Stack.peek()); // "I am on the top now"
System.out.println(Stack.pop()); // "I am on the top now"
System.out.println(Stack.peek()); // "Hello World
}
}