public class QueueB {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
static class Queue {
static Node head = null;
static Node tail = null;
public boolean isEmpty() {
return head == null && tail == null;
}
// add
public void add(int data) {
Node newNode = new Node(data);
if(head == null) {
head = tail = newNode;
return;
}
tail.next = newNode;
tail = newNode;
}
// remove
public int remove() {
if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
int front = head.data;
// last element deleted
if (tail == head) {
tail = head = null;
} else {
head = head.next;
}
return front;
}
// peek
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
return head.data;
}
}
public static void main(String args[]) {
Queue q = new Queue();
q.add(1);
q.add(2);
q.add(3);
// adding condition that works like a circular queue
System.out.println(q.remove()); // prints 1
q.add(4);
System.out.println(q.remove()); // prints 2
q.add(5);
// queue now contains 3,4,5 in order
while (!q.isEmpty()) {
System.out.println(q.peek());
q.remove();
}
}
}
output:
1 2
3
4
5
No comments:
Post a Comment