-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
90 lines (80 loc) · 1.58 KB
/
Stack.java
File metadata and controls
90 lines (80 loc) · 1.58 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
89
90
package structures;
import java.util.ArrayList;
import java.util.NoSuchElementException;
/**
* A generic stack implementation.
*
* @author ru-nb-cs111
*
* @param <T> Parameter type for items in the stack.
*/
public class Stack<T> {
/**
* Items in the stack.
*/
private ArrayList<T> items;
/**
* Initializes stack to empty.
*/
public Stack() {
items = new ArrayList<T>();
}
/**
* Pushes a new item on top of stack.
*
* @param item Item to push.
*/
public void push(T item) {
items.add(item);
}
/**
* Pops item at top of stack and returns it.
*
* @return Popped item.
* @throws NoSuchElementException If stack is empty.
*/
public T pop()
throws NoSuchElementException {
if (items.isEmpty()) {
//return null;
throw new NoSuchElementException("can't pop from an empty stack");
}
return items.remove(items.size()-1);
}
/**
* Returns item on top of stack, without popping it.
*
* @return Item at top of stack.
* @throws NoSuchElementException If stack is empty.
*/
public T peek()
throws NoSuchElementException {
if (items.size() == 0) {
//return null;
throw new NoSuchElementException("can't peek on an empty stack");
}
return items.get(items.size()-1);
}
/**
* Tells if stack is empty.
*
* @return True if stack is empty, false if not.
*/
public boolean isEmpty() {
return items.isEmpty();
}
/**
* Returns number of items in stack.
*
* @return Number of items in stack.
*/
public int size() {
return items.size();
}
/**
* Empties the stack.
*/
public void clear() {
items.clear();
}
}