Skip to content

Commit a1019d4

Browse files
committed
implemented a stack in java
1 parent 65599ee commit a1019d4

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import java.util.List;
2+
import java.util.ArrayList;
3+
4+
5+
public class StackTest {
6+
7+
public static void main(String[] args) {
8+
IStack<Integer> intStack = new Stack<>();
9+
10+
intStack.push(4);
11+
intStack.push(5);
12+
intStack.push(9);
13+
14+
System.out.println(intStack.pop());
15+
System.out.println(intStack.size());
16+
System.out.println(intStack.peek());
17+
}
18+
19+
}
20+
21+
22+
interface IStack<T> {
23+
/*
24+
* 'pop' removed the last element from the stack and returns it
25+
*/
26+
T pop();
27+
28+
/*
29+
* 'push' adds an element to at the end of the stack and returns the new size
30+
*/
31+
int push(T element);
32+
33+
/*
34+
* 'size' returns the length of the stack
35+
*/
36+
int size();
37+
38+
/*
39+
* 'peek' returns the first element of the stack
40+
*/
41+
T peek();
42+
}
43+
44+
45+
public class Stack<T> implements IStack<T> {
46+
47+
private List<T> list;
48+
49+
public Stack() {
50+
this.list = new ArrayList<>();
51+
}
52+
53+
public T pop() {
54+
return this.list.remove(this.size() - 1);
55+
}
56+
57+
public int push(T element) {
58+
this.list.add(element);
59+
return this.size();
60+
}
61+
62+
public int size() {
63+
return this.list.size();
64+
}
65+
66+
public T peek() {
67+
return this.list.get(this.size() - 1);
68+
}
69+
70+
}
71+
72+

0 commit comments

Comments
 (0)