-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenericLinkedStack.java
66 lines (52 loc) · 1.17 KB
/
GenericLinkedStack.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
59
60
61
62
63
64
65
66
import java.lang.NullPointerException ;
import java.lang.IllegalStateException ;
public class GenericLinkedStack<E> implements Stack<E>{
private static class Elem<T> {
private T info;
private Elem<T> next;
private Elem(T info, Elem<T> next) {
this.info = info;
this.next = next;
}
}
private Elem<E> top;
private int size ;
public GenericLinkedStack(){
top = null ;
size = 0 ;
}
public void push(E elem){
if( elem == null ) {
throw new NullPointerException("Cannot push a null object into a stack") ;
}
top = new Elem<E>(elem,top);
size++ ;
}
public boolean isEmpty() {
return top == null ;
}
public E pop() {
if(isEmpty()) {
throw new EmptyStackException("Cannot pop an object from an empty stack") ;
}
//stack in not empty (solved)
E tmp = top.info;
top = top.next;
size-- ;
return tmp;
}
public E peek(){
if(isEmpty()){
throw new IllegalStateException("Cannot peek an object from an empty stack") ;
}
// stack is not empty solved
return top.info;
}
public int getSize() {
return size ;
}
public void clear() {
top = null ;
size = 0 ;
}
}