forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
79 lines (68 loc) · 1.69 KB
/
Stack.java
File metadata and controls
79 lines (68 loc) · 1.69 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
package com.examplehub.datastructures.stack;
import java.util.ArrayList;
import java.util.EmptyStackException;
public class Stack<E> {
/** Stack which stores elements. */
private ArrayList<E> stack;
public Stack() {
this.stack = new ArrayList<>();
}
/**
* Pushes an item onto the top of this stack.
*
* @param item the item to be pushed onto this stack.
* @return the {@code item} argument.
*/
public E push(E item) {
stack.add(item);
return item;
}
/**
* Removes the object at the top of this stack and returns that object as the value of this
* function.
*
* @return The object at the top of this stack (the last pushed item).
*/
public E pop() {
if (empty()) {
throw new EmptyStackException();
}
return stack.remove(stack.size() - 1);
}
/**
* Looks at the object at the top of this stack without removing it from the stack.
*
* @return the object at the top of this stack (the last item pushed).
* @throws EmptyStackException if the stack is empty.
*/
public E peek() {
if (empty()) {
throw new EmptyStackException();
}
return stack.get(size() - 1);
}
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in this stack.
*/
int size() {
return stack.size();
}
/**
* Returns {@code true} if this stack contains no elements.
*
* @return {@code true} if this stack contains no elements, otherwise {@code false}.
*/
public boolean empty() {
return size() == 0;
}
/** Clear all elements in the stack. */
public void clear() {
stack.clear();
}
@Override
public String toString() {
return stack.toString();
}
}