-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListStack.java
58 lines (47 loc) · 1.08 KB
/
ListStack.java
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
import java.util.LinkedList;
/*
This class implements the Stack interface and provides
implementations for the stub methods defined in the stack
interface. This class makes the stack data structure using
linked lists.
*/
public class ListStack<T> implements Stack<T> {
// making a stack as a list
private LinkedList<T> stack;
// default constructor creating the stack list
public ListStack() {
stack = new LinkedList<T>();
}
@Override
public void push(T element) {
stack.addFirst(element);
}
@Override
public T pop() {
// save the top element of stack before removing it
T element = stack.get(0);
stack.remove(0);
return element;
}
@Override
public T peek() {
return stack.get(0);
}
@Override
public boolean isEmpty() {
return stack.size() == 0;
}
@Override
public int size() {
return stack.size();
}
@Override
public String toString() {
String output = "";
for (int i = 0; i < stack.size(); i++) {
// add each number to the string
output += stack.get(i) + " ";
}
return output;
}
}