-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
73 lines (61 loc) · 1.52 KB
/
Queue.java
File metadata and controls
73 lines (61 loc) · 1.52 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
package practice;
class Node {
int value;
Node next;
Node(int value) {
this.value = value;
this.next = null;
}
}
class Que {
Node front;
Node rear;
// ENQUEUE (add at rear)
public void add(int value) {
Node newNode = new Node(value);
if (rear == null) {
front = rear = newNode;
return;
}
rear.next = newNode;
rear = newNode;
}
// PEEK (front element)
public int peek() {
if (front == null) return -1;
return front.value;
}
// DEQUEUE (remove from front)
public int remove() {
if (front == null) return -1;
int ans = front.value;
front = front.next;
// if queue becomes empty
if (front == null) {
rear = null;
}
return ans;
}
// DISPLAY
public void display() {
Node temp = front;
while (temp != null) {
System.out.print(temp.value + " -> ");
temp = temp.next;
}
System.out.println("null");
}
}
public class Queue {
public static void main(String[] args) {
Que q = new Que();
q.add(8);
q.add(65);
q.add(97);
q.add(52);
q.display(); // 8 -> 65 -> 97 -> 52 -> null
System.out.println(q.peek()); // 8
System.out.println(q.remove()); // 8
q.display(); // 65 -> 97 -> 52 -> null
}
}