Q5. [10 marks] Implement a function Sum(Stack S) in pseudocode to add up all elements of stack S. In the end of your algorithm, the stack S becomes empty. Denoting the size of stack S by |S|, give the time complexity of your algorithm. In this question, only the operations defined in Stack ADT as shown in Fig: 2 are allowed. For example, for(i=0; i<n; i++) ans+=S[i] is a wrong algorithm, since visiting an arbitrary element by index is not a valid stack operation. Instead, you can only touch the top element of a stack by Pop or Top. When S1 and Sz in Fig: 1 are fed to your algorithm, Sum(S1) and Sum(Sz) should return 14 and 8 respectively.
4
S1
Sz
Fig
Two Demo Stacks