8000 stack using ll · anmolpant/Coding-Ninjas-Java@eec4a14 · GitHub
[go: up one dir, main page]

Skip to content

Commit eec4a14

Browse files
committed
stack using ll
1 parent 20ce102 commit eec4a14

File tree

4 files changed

+104
-0
lines changed

4 files changed

+104
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
public class Node<T> {
3+
4+
T data;
5+
Node<T> next;
6+
7+
Node(T data){
8+
this.data = data;
9+
next = null;
10+
}
11+
12+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
2+
public class StackEmptyException extends Exception {
3+
4+
/**
5+
*
6+
*/
7+
private static final long serialVersionUID = 1L;
8+
9+
10+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
public class StackUse {
3+
4+
public static void main(String[] args) throws StackFullException {
5+
6+
StackUsingLL<Integer> stack = new StackUsingLL<>();
7+
8+
// StackUsingArray stack = new StackUsingArray(3);
9+
for(int i = 1; i <= 5; i++){
10+
stack.push(i);
11+
}
12+
13+
while(!stack.isEmpty()){
14+
try {
15+
System.out.println(stack.pop());
16+
} catch (StackEmptyException e) {
17+
// Never reach here
18+
}
19+
}
20+
21+
}
22+
23+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
2+
public class StackUsingLL<T> {
3+
4+
5+
private Node<T> head;
6+
private int size;
7+
8+
public StackUsingLL() {
9+
head = null;
10+
size = 0;
11+
}
12+
13+
int size(){
14+
return size;
15+
}
16+
boolean isEmpty(){
17+
return size() == 0; // head == null
18+
}
19+
20+
T top() throws StackEmptyException{
21+
if(size() == 0){
22+
//StackEmptyException e = new StackEmptyException();
23+
//throw e;
24+
throw new StackEmptyException();
25+
}
26+
return head.data;
27+
}
28+
29+
void push(T element){
30+
31+
Node<T> newNode = new Node<T>(element);
32+
newNode.next = head;
33+
head = newNode;
34+
size++;
35+
36+
}
37+
38+
T pop() throws StackEmptyException{
39+
if(size() == 0){
40+
//StackEmptyException e = new StackEmptyException();
41+
//throw e;
42+
throw new StackEmptyException();
43+
}
44+
T tempdata = head.data;
45+
head = head.next;
46+
size--;
47+
return tempdata;
48+
49+
}
50+
51+
52+
53+
54+
55+
56+
57+
58+
59+
}

0 commit comments

Comments
 (0)
0