8000 double stack · anmolpant/Coding-Ninjas-Java@20ce102 · GitHub
[go: up one dir, main page]

Skip to c 8000 ontent

Commit 20ce102

Browse files
committed
double stack
1 parent 26dbf13 commit 20ce102

File tree

6 files changed

+116
-0
lines changed

6 files changed

+116
-0
lines changed
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: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
2+
public class StackFullException extends Exception {
3+
4+
/**
5+
*
6+
*/
7+
private static final long serialVersionUID = 1L;
8+
9+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
public class StackUse {
3+
4+
public static void main(String[] args) throws StackFullException {
5+
6+
StackUsingArray stack = new StackUsingArray(3);
7+
for(int i = 1; i <= 5; i++){
8+
stack.push(i);
9+
}
10+
11+
while(!stack.isEmpty()){
12+
try {
13+
System.out.println(stack.pop());
14+
} catch (StackEmptyException e) {
15+
// Never reach here
16+
}
17+
}
18+
19+
}
20+
21+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
2+
public class StackUsingArray {
3+
4+
private int data[];
5+
private int top; // is the index of topmost element of stack
6+
7+
public StackUsingArray() {
8+
data = new int[10];
9+
top = -1;
10+
}
11+
12+
public StackUsingArray(int capacity) {
13+
data = new int[capacity];
14+
top = -1;
15+
}
16+
17+
public boolean isEmpty(){
18+
// if(top == -1){
19+
// return true;
20+
// }else{
21+
// return false;
22+
// }
23+
return (top == -1);
24+
}
25+
26+
public int size(){
27+
return top + 1;
28+
}
29+
30+
public int top() throws StackEmptyException{
31+
if(size() == 0){
32+
//StackEmptyException
33+
StackEmptyException e = new StackEmptyException();
34+
throw e;
35+
}
36+
return data[top];
37+
}
38+
39+
public void push(int elem) throws StackFullException{
40+
if(size() == data.length){
41+
// // Stack Full
42+
// StackFullException e = new StackFullException();
43+
// throw e;
44+
doubleCapacity();
45+
46+
}
47+
top++;
48+
data[top] = elem;
49+
}
50+
51+
private void doubleCapacity() {
52+
int temp[] = data;
53+
data = new int[2 * temp.length];
54+
for(int i = 0; i <= top; i++){
55+
data[i] = temp[i];
56+
}
57+
58+
}
59+
60+
public int pop() throws StackEmptyException{
61+
if(size() == 0){
62+
//StackEmptyException
63+
StackEmptyException e = new StackEmptyException();
64+
throw e;
65+
}
66+
int temp = data[top];
67+
top--;
68+
return temp;
69+
70+
}
71+
72+
73+
74+
75+
76+
}

0 commit comments

Comments
 (0)
0