NEED HELP \"Write a method called stackSum that returns an int and has no parame
ID: 3824693 • Letter: N
Question
NEED HELP
"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-" The following rubric will be used: 1. Create the basic template common to all Java programs. 2. Give the correct signature for the specified method/function. 3. Access the calling object's stack. 4. Effectively accesses the data members and methods. 5. Implement a base case and recursive case in the solution. 6. Effectively return the correct sum of a stack using recursion. 7. Leave the calling object's stack unchanged. 8. Test the recursive function/method using a main driver. 9. Check the program for errors and omissions and debug. 10. Successfully execute the file with the appropriate output to the console. A score of 5, for example, would mean the program demonstrated 5 out of the 10 objectives.Explanation / Answer
HI, Please find my implementation.Please let me know in case of any issue.
import java.util.NoSuchElementException;
public class LinkedStack {
class LSNode{
private int info;
private LSNode link;
public LSNode(int val){
this.info = val;
}
}
private LSNode top;
public void push(int newVal){
LSNode newNode = new LSNode(newVal);
if(top!=null){
newNode.link=top;
}
top=newNode;
}
public int pop(){
if(top==null)
throw new NoSuchElementException("Underflow Exception") ;
LSNode temp = top;
top=top.link;
return temp.info;
}
public int peek(){
if(top==null)
throw new NoSuchElementException("Underflow Exception") ;
return top.info;
}
public int stackSum(){
return stackSumUtil(top);
}
private int stackSumUtil(LSNode node){
if(node == null)
return 0;
return getInfo(node) + stackSumUtil(getLink(node));
}
public String toString(){
if(top==null)
return null;
LSNode current=top;
StringBuilder str=new StringBuilder();
while(current!=null){
str.append(current.info + " ");
current=current.link;
}
return str.toString();
}
public int getInfo(LSNode node){
return node.info;
}
public LSNode getLink(LSNode node){
return node.link;
}
public static void main(String[] args) {
// creating Object
LinkedStack stack = new LinkedStack();
stack.push(-6);
stack.push(4);
stack.push(2);
stack.push(10);
stack.push(8);
System.out.println("Sum : "+stack.stackSum());
}
}
/*
Sample run:
Sum : 18
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.