forked from Vatsalparsaniya/Data-Structure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.java
More file actions
52 lines (42 loc) · 1.26 KB
/
Copy pathstack.java
File metadata and controls
52 lines (42 loc) · 1.26 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
import java.util.EmptyStackException;
import java.util.Iterator;
import java.util.LinkedList;
public class Stack <T> implements Iterable <T> {
private LinkedList <T> list = new java.util.LinkedList <T>();
// Create an empty stack
public Stack() { }
// Create a Stack with an initial element
public Stack(T firstElem) {
push(firstElem);
}
// Return the number of elements in the stack
public int size() {
return list.size();
}
// Check if the stack is empty
public boolean isEmpty() {
return size() == 0;
}
// Push an element on the stack
public void push(T elem) {
list.addLast(elem);
}
// Pop an element off the stack
// Throws an error is the stack empty
public T pop() {
if (isEmpty())
throw new EmptyStackException();
return list.removeLast();
}
// Peek the top of the stack without removing an element
// Throws an exception if the stack is empty
public T peek() {
if (isEmpty())
throw new EmptyStackException();
return list.peekLast();
}
// Allow users to iterate through the stack using an iterator
@Override public Iterator <T> iterator () {
return list.iterator();
}
}