c++ - Recursive solution for detecting negatives? -



c++ - Recursive solution for detecting negatives? -

i'm writing programme detects number of negatives in stack. first snippet of code below achieves goal iteratively (i think). i'm trying accomplish same goal recursively now. sec snippet have far.. unable create work.

int negcount = 0; while(mystack.size() > 0) { if(mystack.top() < 0) { negcount++; } mystack.pop(); }

this tried create function recursive.. there wrong way loop setup i'm not sure what..

size_t r_approach (stack<int> my_stack) { int cnt = 0; while (mystack.size() > 0) { if (mystack.top() >= 0) { cout << " nothing" << endl; mystack.pop(); } else { cnt++; mystack.pop(); r_approach(mystack); } } cout << cnt << endl; }

if solution pretends recursive, why while loop? supposed iterate using recursion not loop:

size_t r_approach (stack<int> & mystack, size_t count) { if(mystack.size() == 0) homecoming count; int t = mystack.top(); mystack.pop(); homecoming r_approach(mystack, count+(t<0)); }

note that, in order avoid copying stack in each iteration, mystack parammeter passed reference. may find unusual count parammeter too. tail recursion practice since compilers can optimize code.

edit (to reply op comment)

if want remove parameter (count) , don't need tail recursion, can maintain count using homecoming value:

size_t r_approach (stack<int> & mystack) { if(mystack.size() == 0) homecoming 0; int t = mystack.top(); mystack.pop(); homecoming (t<0)+r_approach(mystack); }

other alternative allow maintain tail recursion wrap initial implementation gave you:

size_t r_approach_imp (stack<int> & mystack, size_t count) { if(mystack.size() == 0) homecoming count; int t = mystack.top(); mystack.pop(); homecoming r_approach_imp(mystack, count+(t<0)); } size_t r_approach(stack<int> & mystack) { homecoming r_approach_imp (mystack, 0); }

c++ loops

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -