Write a method called stackSum that returns an int and has no parameters which w
ID: 3860961 • Letter: W
Question
Write a method called stackSum that returns an int and has no parameters which will find the sum of a stack using a recursive technique and leave the stack unchanged. Test the method in a driver program with the following items pushed onto a stack in the following hardcoded order: -6, 4, 2, 10, 8. The output of the program should display the sum in a message to the console. Assume the method is a member of a linked stack class called LinkedStack that has a private data member: top, and methods: getInfo() and getLink(). The data member top is of type: LSNode (linked stack node), and each LSNode has data members: info and link.
Must include the following:
Create the basic template common to all C++ programs.
Give the correct signature for the specified method/function.
Access the calling object’s stack.
Effectively accesses the data members and methods.
Implement a base case and recursive case in the solution.
Effectively return the correct sum of a stack using recursion.
Leave the calling object’s stack unchanged.
Test the recursive function/method using a main driver.
Check the program for errors and omissions and debug.
Successfully execute the file with the appropriate output to the console.
C++
Explanation / Answer
#include<iostream>
using namespace std;
struct LSNode {
private:
int info;
LSNode* link;
public:
LSNode (int data, LSNode* next) {
info = data;
link = next;
}
int getInfo() {
return info;
}
LSNode* getLink() {
return link;
}
};
LSNode *stackTop = NULL;
void push(int data) {
LSNode *tmp = new LSNode(data, stackTop);
stackTop = tmp;
}
int stackSum(LSNode* top) {
if (top == NULL)
return 0;
else
return top->getInfo() + stackSum(top->getLink());
}
int main() {
push(-6);
push(4);
push(2);
push(10);
push(8);
cout << "Sum is: " << stackSum(stackTop) << endl;
}
Here is the complete code. The required mehod and the test main method have been highlighted. I hope this helps!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.