File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed
src/test/java/com/thealgorithms/datastructures/queues Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ public class ImplementQueue {
2+ // implementation of queue using array
3+ // Queue Algorith type:FIFO (First Come First Out)
4+
5+ // create Queue class
6+ public static class Queue {
7+ int arr [];
8+ int size ;
9+ int rear ;
10+
11+ public Queue (int n ) {
12+ arr = new int [n ];
13+ size = n ;
14+ rear = -1 ; // initizalation of the rear
15+ }
16+
17+ // operations
18+
19+ // IsEmpty() method
20+ public boolean isEmpty () {
21+ return rear == -1 ; // when rear will be -1 that means no element is there in the queue
22+ }
23+
24+ public boolean isOverflow () {
25+
26+ return rear == size - 1 ;
27+ }
28+
29+ // add() method
30+ public void add (int data ) {
31+ if (isOverflow ()) {
32+ System .out .println ("Queue is full now !!" );
33+ }
34+ rear = rear + 1 ;
35+ arr [rear ] = data ;
36+ }
37+
38+ // remove() method
39+ public int remove () {
40+ if (isEmpty ()) {
41+ System .out .println ("Queue is Empty !!" );
42+ return -1 ;
43+ }
44+ int front = arr [0 ]; // 1 2 3 4 here front will point to 1
45+ // now replacing the 1 to 2 and 2 to 3 and so on..
46+ for (int i = 0 ; i < rear ; i ++) {
47+ arr [i ] = arr [i + 1 ];
48+ }
49+ rear = rear - 1 ;
50+ return front ; // removed element
51+ }
52+
53+ // peek() method
54+
55+ public int peek () {
56+ if (isEmpty ()) {
57+ System .out .println ("No element is there" );
58+ return -1 ;
59+ }
60+ return arr [0 ];
61+ }
62+
63+ }
64+
65+ public static void main (String [] args ) {
66+ Queue q = new Queue (5 );
67+ q .add (1 );
68+ q .add (9 );
69+ q .add (10 );
70+
71+ System .out .println ("Front Element:" + q .peek ());
72+ System .out .println ("Removed Element:" + q .remove ());
73+
74+ q .add (90 );
75+ q .add (100 );
76+
77+ q .add (120 );
78+ q .add (56 );
79+ System .out .println (q .isOverflow ());
80+
81+ }
82+ }
You can’t perform that action at this time.
0 commit comments