Reverse K elements problem solution in java

Problem : You have a ‘n’ number of elements. You want to reverse a set of elements. Let it be ‘K’ number of elements. How will you solve using a queue and stack. Implement it in java.

Solution in java:

  • ·       Create a public class with main() function.
  • ·       A member function with the input parameters of queue and the ‘k’ value. It checks whether the queue is null or queue’s size is less than k or k is less than 0.
  • ·       If any one of the above is true, it returns the queue.
  • ·       Create an integer stack. Push ‘n’ number of elements into the stack.
  • ·       Delete(enque) the ‘K’ number of elements and store it into queue.
  • ·       Move the remaining elements from the front end to the rear end to preserve the order.

Program:

import java.util.LinkedList;

import java.util.Queue;

import java.util.Stack;

public class ReverseFKElements {

    public static Queue<Integer> reverseFirstK(Queue<Integer> queue1, int k) {

        if (queue1 == null || queue1.size() < k || k <= 0) {

            return queue1;

        }

        Stack<Integer> stack1 = new Stack<>();

        // insert(Push) the elements into the stack.  let it be the first 'K' elements

        for (int i = 0; i < k; i++) {

            stack1.push(queue1.poll());

        }

        // Delete(Enqueue) the elements from the stack and store it into queue.

        while (!stack1.isEmpty()) {

            queue1.add(stack1.pop());

        }

        // Move the remaining elements from the front end to the rear end to preserve the order

        int size = queue1.size();

        for (int i = 0; i < size - k; i++) {

            queue1.add(queue1.poll());

        }

        return queue1;

    }

    public static void main(String[] args) {

        Queue<Integer> queue1 = new LinkedList<>();

        queue1.add(23);

        queue1.add(34);

        queue1.add(45);

        queue1.add(56);

        queue1.add(67);

        queue1.add(78);

        queue1.add(89);

        int k =4 ;

        System.out.println("The original queue with elements: " + queue1);

        queue1 = reverseFirstK(queue1, k);

        System.out.println("The elements of Queue after reversing first " + k + " elements: " + queue1);

    }

}

Output is given below…

C:\raji\blog>javac ReverseFKElements.java

C:\raji\blog>java ReverseFKElements

The original queue with elements: [23, 34, 45, 56, 67, 78, 89]

The elements of Queue after reversing first 4 elements: [56, 45, 34, 23, 67, 78, 89]

Note: This is the one of the efficient method to solve this program. Keep coding!!!!

No comments:

Post a Comment