c++ - Recursive solution for detecting negatives? -
I am writing a program that detects the number of negatives in a stack. The first snippet of code below gets the goal (I think) lightly. I am just trying to achieve the same goal. The second is the snippet I have done so far .. but I am unable to work it successfully.
int negcount = 0; While (mystack.size ()> 0) {if (mystack.top () & lt; 0) {negcount ++; } Mystack.pop (); } It is that I tried to make the function recursive. Of course there is something wrong with the loop method but I am not sure whether .. size_t r_approach (stack my_stack) {int cnt = 0; While (mystack.size ()> 0) {if (mystack.top ()> = 0) {cout & lt; & Lt; "Nothing" & lt; & Lt; Endl; Mystack.pop (); } Else {cnt ++; Mystack.pop (); R_approach (mystack); }} Cout & lt; & Lt; CNT & LT; & Lt; Endl; }
If your solution pretends to be recurring, while < / Code> loop? You should not be repeated using the recursive: size_t r_approach (stack & lt; int & gt; & mystack, size_t count) {if (mystack.size () == 0 ) Return calculation; Int t = mystack.top (); Mystack.pop (); Return r_approach (MyStack, Guin + (T & L; 0)); } Note, to avoid copying the stack in each walk, the MyStack parameter has now been passed as a reference, you can find strange There is also a parameter that is count also it is a good practice to get the tail repeatable, because some compiler can customize the code. Edit (to respond to OP comment) If you want to remove additional parameters and you need to repeat tail If not, you can count only using the return value:
size_t r_approach (stack & gt; int & gt; & mystack) {If (mystack.size () == 0) returns 0; Int t = mystack.top (); Mystack.pop (); Return (T & L; 0) + R-Agroche (Mystak); } Another option which allows you to have tail recurrence is to wrap the initial implementation. I:
size_t r_approach_imp (stack & Lt; int & gt;; MySTAC, size_T calculation) {if (mystack.size () == 0) Return calculation; Int t = mystack.top (); Mystack.pop (); Return r_approach_imp (MyStack, GIN + (T & LT; 0)); } Size_t r_approach (stack & lt; int & gt; & mystack) {return r_approach_imp (MyStack, 0); }
Comments
Post a Comment