Queue is a linear data structure. It has a front end which points out the beginning and rear end which points out the ending of the queue.
Generally, deletion occurs in front end. Insertions occurs
in rear end.
Process:
- First , a java class is written with a constructor. x
- We create a queue as linked list and declare an object instance.
- The constructor checks the ‘k’ value and rotates the queue by moving the front end element to rear end until the ‘k’th element as front end.
- Inside the main function, create an object for queue. The data’s are inserted in the queue.
- The input value is received from user. The queue object and k value is passed to the function.
- The function returns the rotated queue and it is displayed in the output screen.
Program:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class RotateaQueue {
// function
definition for rotation
public static void
rotateaQueue(Queue<Integer> queue1, int k) {
int q_size =
queue1.size();
k = k %
q_size;
for (int i =
0; i < k; i++) {
// Let us
move the frontend element to the rearend
int
frontend = queue1.poll();
queue1.add(frontend);
}
}
public static void
main(String[] args) {
Queue<Integer> queue1 = new LinkedList<>();
Scanner myObj1
= new Scanner(System.in);
queue1.add(11);
queue1.add(32);
queue1.add(25);
queue1.add(40);
queue1.add(15);
queue1.add(20);
System.out.println("Enter the K value from which the queue is going
to be rotated:");
int k=
myObj1.nextInt();
System.out.println("Original Queue: " + queue1);
rotateaQueue(queue1, k);
System.out.println("Rotated Queue: " + queue1);
}
}
Output:
C:\raji\blog>java RotateaQueue
Enter the K value from which the queue is going to be
rotated:
4
Original Queue: [11, 32, 25, 40, 15, 20]
Rotated Queue: [15, 20, 11, 32, 25, 40]
That’s all. The java program to implement the rotatation of a queue by k positions is running successfully.
Keep coding!!!
No comments:
Post a Comment