-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_basic_3.java
More file actions
104 lines (85 loc) · 2.65 KB
/
queue_basic_3.java
File metadata and controls
104 lines (85 loc) · 2.65 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
96
97
98
99
100
101
102
103
104
package stack_and_queue_week_2;
public class queue_basic_3 {
// Using linked list.
//*** This is the most efficient way.
static class Node{
int data;
Node next;
Node(int data){
this.data = data;
next = null;
}
}
static class Queue{
static Node head = null; // Traditional Front
static Node tail = null; // Rear
public static boolean isEmpty(){
return head == null && tail == null;
}
public static void add(int data){
Node newNode = new Node(data);
if(tail == null){ // if the current linked list is empty.
head = tail = newNode;
return;
}
// Insert will be rear = tail
tail.next = newNode;
tail = newNode;
}
public static int remove(){
if(isEmpty()){ // no element in queue.
System.out.println("Empty Queue.");
return -1;
}
if(head.next==null){ // single element in queue
tail = null;
}
int front = head.data;
head = head.next;
return front;
}
public static int peek(){
if(isEmpty()){ // no element in queue.
System.out.println("Empty Queue.");
return -1;
}
return head.data;
}
}
public static void main(String[] args) {
Queue queue = new Queue();
queue.add(12);
queue.add(13);
queue.add(15);
System.out.println("Queue: ");
while (!queue.isEmpty()){
System.out.print(queue.peek()+" -> ");
queue.remove();
}
System.out.print("null.");
System.out.println();
System.out.println("Queue is empty ?\nAns. "+queue.isEmpty());
System.out.println("=========================================");
System.out.println();
queue.add(12);
queue.add(13);
queue.add(15);
Node currentNode = queue.head;
while (currentNode!=null){
System.out.print(currentNode.data+" -> ");
currentNode = currentNode.next;
}
System.out.print("null.");
System.out.println();
queue.remove();
// again relocate the head
currentNode = queue.head;
System.out.println("after remove method call.");
while (currentNode!=null){
System.out.print(currentNode.data+" -> ");
currentNode = currentNode.next;
}
System.out.print("null.");
System.out.println();
}
}