forked from ows-ali/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
66 lines (58 loc) · 1.44 KB
/
Stack.java
File metadata and controls
66 lines (58 loc) · 1.44 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
/*
* Data Structures and Algorithms.
* Copyright (C) 2016 Rafael Guterres Jeffman
*
* See the LICENSE file accompanying this source code, for
* licensing restrictions that might apply.
*
*/
package datastructures;
import java.util.EmptyStackException;
/**
* Implements a LIFO protocol for data.
*/
public class Stack<T> {
private Vector<T> data = new Vector<>();
/**
* Add a new value to the stack.
* @param value The value to be on the top of the stack.
*/
public void push(T value) {
this.data.append(value);
}
/**
* Remove the element on the top of the stack, returning it.
* @return The element at the top of the stack.
*/
public T pop() {
if (isEmpty())
throw new EmptyStackException();
T result = peek();
data.remove(data.size()-1);
return result;
}
/**
* Retrieve the element at the top of the stack, without removing it
* from the stack.
* @return The element at the top of the stack, or null if it's empty.
*/
public T peek() {
if (isEmpty())
return null;
return data.get(data.size()-1);
}
/**
* Check if the stack is empty.
* @return True if there's no element on the stack, false otherwise.
*/
public boolean isEmpty() {
return data.size() == 0;
}
/**
* Return the number of elements on the stack currently stored.
* @return The number of elements stored.
*/
public int size() {
return data.size();
}
}