You are on page 1of 5

Name: Aditya Kumar

Roll No: 02 (O)


University Roll No: 191500057

Question No 20 Write a program to copy all the elements of one queue into another
queue in reverse using stack and print both the queues.
Solution
/*
Name: Aditya Kumar
Section: O
University Roll No.: 191500057
Class Roll No.: 02
*/
import java.util.Stack;

public class QueueUsingLL {


class Node {
int data;
Node next;

public Node(int data) {


this.data = data;
}
}

Node head;
Node tail;
int size;
public QueueUsingLL() {
head = null;
tail = null;
size = 0;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return (size==0);
}
public void enqueue(int data) {
QueueUsingLL.Node newnode = new QueueUsingLL.Node(data);
if(head==null){
head = newnode;
tail = newnode;
}
else{
tail.next = newnode;
tail = newnode;
}
size++;
}
public int dequeue() {
if(head == null){
return -1;
}
int data = head.data;
head = head.next;
size--;
return data;
}
public int front() {
if(head==null){
return -1;
}
return head.data;
}
public void moveToRear(){
QueueUsingLL.Node curr = head;
if(head == null){
System.out.println("Not possible queue is empty");
return;
}
head = head.next;
tail.next = curr;
tail = curr;

public static void main(String[] args) {


QueueUsingLL q = new QueueUsingLL();
QueueUsingLL q2 = new QueueUsingLL();
Stack<Integer> st = new Stack<>();
System.out.println("Elements stored in the queue 1 are: ");
for(int i = 0;i<10;i++){
q.enqueue(i+5);
st.push(i+5);
System.out.print((i+5)+" ");
}

while(!st.isEmpty()){
q2.enqueue(st.pop());
}
System.out.println("\nAfter copying");
while(!q2.isEmpty()){
System.out.print(q2.dequeue()+" ");
}
}
}

Screen shot of code


Screen shot of output

You might also like