In: Computer Science
Write a function in any functional programming language that will reverse a general list. For example, if an input is (A (B C (D E)) F), output is (F ((E D) C B) A). Please note that any built-in/pre-defined function, e.g., reverse, cannot be used in your answer.
Please DO NOT hard-code any input values, output values in your code.
Please submit a screenshot of where your code got compiled, executed, showing the execution result
Here we can use stack to reverse the list. I have written very easy logic which could be easily understandable.
#include<bits/stdc++.h>
using namespace std;
int main()
{
stack<char> stk;
//taking the complete input first in a string
string s;
cout << "Enter the list to be reversed "; //input message
getline(cin,s);
for(int i = 0; i<s.length(); i++){
stk.push(s[i]); //then pushing each character of the string into stack
}
cout << "Output is "; //output message
//then printing every character one by one
for(int i = 0; i<s.length(); i++){
char k = stk.top();
stk.pop();
if(k== ')'){ // we have to seperately deal with with the brackets.
cout << "(";
}
else if(k == '('){
cout << ")";
}
else{
cout << k;
}
}
}
output will look like below picture. (i have customised the output and input message and it can be removed if required)