-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.java
39 lines (31 loc) · 842 Bytes
/
Stack.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
package linear;
public class Stack {
LinkedList linkedList = new LinkedList();
int size = 0;
void push(int value){
linkedList.insertFirst(value);
size++;
}
int pop(){
if(isEmpty()) throw new EmptyStackException("Cannot pop from an empty stack.");
int deletedNodeValue = linkedList.head.data;
linkedList.deleteFirst();
size --;
return deletedNodeValue;
}
int peek(){
if(isEmpty()) throw new EmptyStackException("Cannot peek from an empty stack.");
return linkedList.head.data;
}
boolean isEmpty(){
return linkedList.head == null;
}
int size(){
return size;
}
}
class EmptyStackException extends RuntimeException {
public EmptyStackException(String message) {
super(message);
}
}