File tree Expand file tree Collapse file tree 6 files changed +127
-0
lines changed
Data Structures in Java/Level 2/Stacks and Queues/Queue_Using_Array Expand file tree Collapse file tree 6 files changed +127
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ public class QueueEmptyException extends Exception {
3
+
4
+ /**
5
+ *
6
+ */
7
+ private static final long serialVersionUID = 7243921724361015813L ;
8
+
9
+ }
Original file line number Diff line number Diff line change
1
+
2
+ public class QueueFullException extends Exception {
3
+
4
+ /**
5
+ *
6
+ */
7
+ private static final long serialVersionUID = -7167634756637168192L ;
8
+
9
+ }
Original file line number Diff line number Diff line change
1
+
2
+ public class QueueUse {
3
+
4
+ public static void main (String [] args ) {
5
+ QueueUsingArray queue = new QueueUsingArray (3 );
6
+ for (int i = 1 ; i <= 5 ; i ++){
7
+ queue .enqueue (i );
8
+ try {
9
+ queue .enqueue (i );
10
+ } catch (QueueFullException e ) {
11
+
12
+ }
13
+ }
14
+
15
+
16
+ while (! queue .isEmpty ()){
17
+ try {
18
+ System .out .println (queue .dequeue ());
19
+ } catch (QueueEmptyException e ) {
20
+ // TODO Auto-generated catch block
21
+ e .printStackTrace ();
22
+ }
23
+ }
24
+
25
+ }
26
+
27
+ }
Original file line number Diff line number Diff line change
1
+
2
+ public class QueueUsingArray {
3
+
4
+ private int data [];
5
+ private int front ; // index at which front element is stored
6
+ private int rear ; // index at which rear element is stored
7
+ private int size ;
8
+
9
+ public QueueUsingArray () {
10
+ data = new int [10 ];
11
+ front = -1 ;
12
+ rear = -1 ;
13
+ size = 0 ;
14
+ }
15
+ public QueueUsingArray ( int capacity ) {
16
+ data = new int [capacity ];
17
+ front = -1 ;
18
+ rear = -1 ;
19
+ size = 0 ;
20
+ }
21
+
22
+ int size (){
23
+ return size ;
24
+ }
25
+
26
+ boolean isEmpty (){
27
+ return size == 0 ;
28
+ }
29
+
30
+ int front () throws QueueEmptyException {
31
+ if (size == 0 ){
32
+ throw new QueueEmptyException ();
33
+ }
34
+ return data [front ];
35
+ }
36
+
37
+ void enqueue (int element ) throws QueueFullException {
38
+
39
+ if (size == data .length ){
40
+ throw new QueueFullException ();
41
+ }
42
+
43
+ if (size == 0 ){
44
+ front = 0 ;
45
+ }
46
+ size ++;
47
+ rear = (rear + 1 ) % data .length ;
48
+ // rear++;
49
+ // if(rear == data.length){
50
+ // rear = 0;
51
+ // }
52
+ data [rear ] = element ;
53
+ }
54
+
55
+ int dequeue () throws QueueEmptyException {
56
+ if (size == 0 ){
57
+ throw new QueueEmptyException ();
58
+ }
59
+ int temp = data [front ];
60
+ front = (front + 1 ) % data .length ;
61
+ // front++;
62
+ // if(front == data.length){
63
+ // front = 0;
64
+ // }
65
+ size --;
66
+ if (size == 0 ){
67
+ front = -1 ;
68
+ rear = -1 ;
69
+ }
70
+ return temp ;
71
+ }
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+ }
You can’t perform that action at this time.
0 commit comments