-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
95 lines (71 loc) · 2.07 KB
/
Copy pathMain.java
File metadata and controls
95 lines (71 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* Queue implementation using Array */
package DataStructuresAndAlgorithms.src.queue.Array;
import java.util.NoSuchElementException;
public class Main {
static class Queue{
private int[] queue;
private int front;
private int back;
public Queue(){
queue = new int[10];
}
// Method to add elements in the Queue
public void add(int val){
if(size() == queue.length){
int newQueue[] = new int[2 * queue.length];
System.arraycopy(queue, 0, newQueue, 0, queue.length);
queue = newQueue;
}
queue[back++] = val;
}
// Method to print size of the Queue
public int size(){
return back - front;
}
// Method to check if Queue is empty
public boolean isEmpty(){
return back == 0;
}
// Method to print top element of the Queue
public int peek(){
if(size() == 0){
throw new NoSuchElementException();
}
return queue[front];
}
// Method to remove top element of the Queue
public int remove(){
if(size() == 0){
throw new NoSuchElementException();
}
int val = queue[front];
queue[front] = 0;
front++;
if(size() == 0){
front = 0;
back = 0;
}
return val;
}
// Method to print the elements of the Queue
public void printQueue(){
for(int i = front; i < back; i++){
System.out.print(queue[i] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Queue queue = new Queue();
System.out.println(queue.isEmpty());
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
queue.printQueue();
System.out.println(queue.remove());
System.out.println(queue.peek());
queue.printQueue();
}
}