Question:
Ram participates in an online gaming contest, where he is asked to code logic in Java to reverse the given word using recursion. Help Ram to perform the same. Check the sample input and output statements for more clarifications.
Function signature should be: public static String reverseString(String str)
Implement the main() inside the class ‘ReverseDriver’
Sample Input/Output 1:
Enter the string: teknoturf
Reversed string is: frutonket
Sample Input/Output 2:
Enter the string: krishna
Reversed string is: anhsirK
Sample Input/Output3:
Enter the string: Hello World
Reversed string is: dlroW olleH
CODE:–
StackDriver.java
import java.util.Stack; import java.util.Scanner; class StackDriver { static Stack<Integer>st=new Stack<>(); static void insert_at_bottom(int x) { if(st.isEmpty()) st.push(x); else { int a= st.peek(); st.pop(); insert_at_bottom(x); st.push(a); } } static void reverse() { if(st.size()>0) { int x= st.peek(); st.pop(); reverse(); insert_at_bottom(x); } } public static void main(String[] args) { Scanner s=new Scanner(System.in); System.out.println("Enter length of List:"); int n=s.nextInt(); if(n==0||n<0) { System.out.println("Invalid Length");} else {for(int i=1;i<=n;i++) { st.push(i);} System.out.println("Elements in Stack "); System.out.println(st); reverse(); System.out.println("Elements in the stack after reversal"); System.out.println(st);} } }
Tags:
binary tree | linear data structure | data structures in c | data structure | heap sort | abdul bari udemy
data structures udemy | coding ninjas data structures | binary tree example | data structure and algorithmic thinking with python | queue geeksforgeeks | data structures in java programming