Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>can't you define your getSum() function in the stack implementation? Or is there any restrictions?</p> <p>Sol-1:</p> <pre><code>template &lt;class Object&gt; Object Stack&lt;Object&gt;::getSum( ) { Object sum = 0; // or memset or other stuffs StackNode&lt;Object&gt; * node = topNode; while (node != NULL) { sum += node-&gt;getElement(); node = node-&gt;getNext(); } return sum; } </code></pre> <p>As Gary mentioned you can also improve efficiency by caching the sum value every time you push or pop (i,e stack is changed) Sol-2:</p> <p>Add a member property which will denote the sum (e,g - sum)</p> <pre><code>template &lt;class Object&gt; Stack&lt;Object&gt;::Stack() { topNode = NULL; this-&gt;sum = 0; // initialize or new object } </code></pre> <p>update the sum whenever a object is pushed</p> <pre><code>template &lt;class Object&gt; void Stack&lt;Object&gt;::push( const Object&amp; data ) { StackNode&lt;Object&gt;* newNode = new StackNode&lt;Object&gt;( data, topNode ); topNode = newNode; this-&gt;sum = this-&gt;sum + data; } </code></pre> <p>same update goes for pop() whenever an object is removed</p> <pre><code>template &lt;class Object&gt; void Stack&lt;Object&gt;::pop() { if (isEmpty()) { throw EmptyStack(); } StackNode&lt;Object&gt; *oldTop = topNode; topNode = topNode-&gt;getNext(); this-&gt;sum = this-&gt;sum - oldTop-&gt;getElement(); delete oldTop; } </code></pre> <p>now your last function getSum()</p> <pre><code>template &lt;class Object&gt; Object Stack&lt;Object&gt;::getSum( ) { return this-&gt;sum; } </code></pre> <p>Sol-1 has O(N) = N cost while Sol-2 has O(N) = 1</p> <p>Now you should be able to use pStack->objectIsEven(pStack->getSum());</p> <p>I think you aren't required to be concerned about threading in your stack implementation otherwise you should use some kind of synchronization mechanism while insert/delete operation to make the stack consistent.</p> <p>Hope this helps. regards,</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload