File tree Expand file tree Collapse file tree 6 files changed +116
-0
lines changed
Data Structures in Java/Level 2/Stacks and Queues/DoubleStack Expand file tree Collapse file tree 6 files changed +116
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ public class StackEmptyException extends Exception {
3
+
4
+ /**
5
+ *
6
+ */
7
+ private static final long serialVersionUID = 1L ;
8
+
9
+
10
+ }
Original file line number Diff line number Diff line change
1
+
2
+ public class StackFullException extends Exception {
3
+
4
+ /**
5
+ *
6
+ */
7
+ private static final long serialVersionUID = 1L ;
8
+
9
+ }
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments