-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack_ll.java
94 lines (62 loc) · 1.24 KB
/
stack_ll.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
public class Node<T> {
T data;
Node<T> next;
Node(T data){
this.data = data;
next = null;
}
}
public class StackUse {
public static void main(String[] args) throws StackFullException {
StackUsingArray stack = new StackUsingArray(3);
for(int i = 1; i <= 5; i++){
stack.push(i);
}
while(!stack.isEmpty()){
try {
System.out.println(stack.pop());
} catch (StackEmptyException e) {
// Never reach here
}
}
}
}
public class StackUsingLL<T> {
private Node<T> head;
private int size;
public StackUsingLL() {
head = null;
size = 0;
}
int size(){
return size;
}
boolean isEmpty(){
return size() == 0; // head == null
}
T top() throws StackEmptyException{
if(size() == 0){
//StackEmptyException e = new StackEmptyException();
//throw e;
throw new StackEmptyException();
}
return head.data;
}
void push(T element){
Node<T> newNode = new Node<T>(element);
newNode.next = head;
head = newNode;
size++;
}
T pop() throws StackEmptyException{
if(size() == 0){
//StackEmptyException e = new StackEmptyException();
//throw e;
throw new StackEmptyException();
}
T tempdata = head.data;
head = head.next;
size--;
return tempdata;
}
}