Question

In: Computer Science

Write a RECURSIVE algorithm (different from the ones your provided in 3) implemented in Java a...

Write a RECURSIVE algorithm (different from the ones your provided in 3) implemented in Java a in a complete Java program to reverse a stack of characters using recursion. You are not allowed to use loop constructs like while, for..etc, and you can only use the following functions on Stack S shown below (15pts)

Provide an explanation of the running time.

You will need to implement your own stack if needed

isEmpty(S)

push(S)

pop(S)

Make your own assumption and your own OOP design on the method(s) signature, inputs, outputs, and the full main program.

Solutions

Expert Solution


import java.util.Stack;
 
class Test {
     
    //  I am using Stack class for implementation of the stacks

    static Stack<Character> s = new Stack<>(); // making an object "s" of stack class.

    // the idea is to write a recursive function insertAtEnd that insert the 
    //topmost element at the end or the bottom-most end of the stack
    
    static void insertAtEnd(char x)
    {
 
        if(s.isEmpty())
            s.push(x);
 
        else
        {
            
            //all the elements are stored in a stack of the function call, until we 
            //reach the end of the Stack. if the stack becomes empty
            // i.e. the s.size() becomes zero, the above mentioned part(base condition) 
            //is executed and the element is inserted at the bottom


            char a = s.peek();         //store the topmost element
            s.pop();                   // remove the topmost element
            insertAtEnd(x);            //recursive call
                                        
            s.push(a);                 //Now we will push back all the elements 
                                       //that are stored in the function
                                       //call stack once the element is inserted at 
                                       //the end or the bottom of stack
        }
    }
     
     // now we will implement a function 
     //reverseStack() that reverses the
     //stack using insertAtEnd() function
   
    static void reverseStack()
    {
        if(s.size() > 0)
        {
             //all the elements are stored in a stack of the 
             //function call until we reach the end of the stack
            
            char x = s.peek();//store the topmost element
            s.pop();          // remove the topmost element
            reverseStack();   // recursive call to the function 
                              //again to reverse the remaining elements
             
            // insert back all the elements stored in the
            //function call, from bottom to the top. Every 
            //element inserted at the end by using the function
            // insertAtEnd()
          
            insertAtEnd(x);
        }
    }
     
    //  Code to check the working of the functions made
    public static void main(String[] args) 
    {
         
        //pushing elements in stack
        s.push('A');
        s.push('B');
        s.push('C');
        s.push('D');
         
        System.out.println("Stack before the Reversal:");
         
        System.out.println(s);
         
        // calling the function to reverse the stack
        reverseStack();
         
        System.out.println("Stack after the Reversal:");
         
        System.out.println(s);
    }
}

I have mentioned all the necessary comments to explain each line of code.

This program takes the worst time complexity of O(n^2).

Explanation:

The idea is to store all values in the stack of the function call until the stack becomes empty or its size becomes zero.

Now, if the stack is empty, insert all stored items one by one at the bottom of the stack.

example:

let the input stack be:

[ E, F, G, H] where E is the topmost element.

so the approach is to insert the topmost element into the bottom of the stack:

  • H is inserted at the bottom as the stack becomes empty and H is the topmost of the function call stack:
    • stack:{H(top)}
  • G is inserted at the bottom as G is the topmost of the function call stack.
    • stack:{H(top),G}
  • F is inserted at the bottom as F is the topmost of the function call stack.
    • stack:{H(top),G,F}
  • E is inserted at the bottom as E is the topmost of the function call stack.
    • stack:{H(top),G,F,E}

the final REVERSED stack is :[ H, G, F, E,]


Related Solutions

Recursion java: 1. Write a recursive algorithm to add all the elements of an array of...
Recursion java: 1. Write a recursive algorithm to add all the elements of an array of n elements 2. Write a recursive algorithm to get the minimum element of an array of n elements 3. Write a recursive algorithm to add the corresponding elements of two arrays (A and B) of n elements. Store the results in a third array C .4. Write a recursive algorithm to get the maximum element of a binary tree 5. Write a recursive algorithm...
Use java .Given a stack S and an element x, write a recursive algorithm that returns...
Use java .Given a stack S and an element x, write a recursive algorithm that returns True if x is in S, or False otherwise. Note that your algorithm should not change the content in S. What is the time complexity of your algorithm?
1. a) Write two algorithms of different time complexity implemented in Java methods in complete Java...
1. a) Write two algorithms of different time complexity implemented in Java methods in complete Java program to reverse a stack of characters. Make your own assumption and your own design on the methods signature, inputs, outputs, and the full main program.
Write a java program with 3 recursive methods that reverse the order of a string. The...
Write a java program with 3 recursive methods that reverse the order of a string. The first recursive method should reverse the order starting from the left selecting the leftmost character as the head and the remaining part of the string as its tail., the second starting from the right selecting the rightmost character as the head and the remaining part of the string on its left as the tail, and the last a recursive method starting from the middle...
**** All these methods should be implemented using RECURSIVE solutions (no looping statements) // Java //...
**** All these methods should be implemented using RECURSIVE solutions (no looping statements) // Java // This method takes an integer array as well as an integer (the starting // index) and returns the sum of the squares of the elements in the array. // This method uses recursion. public int sumSquaresRec(int[] A, int pos) { // TODO: implement this method        return -1; // replace this statement with your own return }    // This method takes a...
Lab #3 – Recursion on Strings Lab Objectives • Be able to write a recursive Java...
Lab #3 – Recursion on Strings Lab Objectives • Be able to write a recursive Java method for Java strings • Be able to make use of exploit natural conversion between strings and integers • Be able to write a driver to call the methods developed for testing Deliverables Submit the report in Word or PDF format with the results of every task listed below. They should show screen capture of your results. The problem String as a sequence of...
2. Go online and find three definitions of "communication" that are different from the ones provided...
2. Go online and find three definitions of "communication" that are different from the ones provided in your textbook. Provide the three definitions and explain the similarities and differences between them. Finally, explain which one you think does the best job of defining "communication." 3. Name three people who you feel use communication effectively in their jobs and explain what they do that makes them effective communicators.
java Write a recursive program to reverse a positive integer. . Your method should take a...
java Write a recursive program to reverse a positive integer. . Your method should take a non negative integer as a parameter and return the reverse of the number as an integer. e.g. if you pass 12345, your method should return 54321.
Write a recursive algorithm replace (start) to replace the value of each element of A with...
Write a recursive algorithm replace (start) to replace the value of each element of A with that of the next element in A. A is a singly linked list.
1) a. Write a C++ program for the recursive algorithm that removes all occurrences of a...
1) a. Write a C++ program for the recursive algorithm that removes all occurrences of a specific character from a string b. Write the pseudocode for the program.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT