Question

JAVA language Add a recursive method to the program shown in the previous section that states...

JAVA language

Add a recursive method to the program shown in the previous section that states
how many times a particular value appears on the stack.

Code:

class Stack {

protected Node top;

Stack() {

top = null; }

boolean isEmpty() {

return( top == null); }

void push(int v) {

Node tempPointer;

tempPointer = new Node(v);

tempPointer.nextNode = top;

top = tempPointer; }

int pop() {

int tempValue;

tempValue = top.value;

top = top.nextNode;

return tempValue; }

void printStack() {

Node aPointer = top;

String tempString = "";

while (aPointer != null) {

tempString = tempString + aPointer.value + "\n";

aPointer = aPointer.nextNode; }

System.out.println(tempString); }

boolean hasValue(int v) {

if (top.value == v) {

return true; }

else {

return hasValueSubList(top,v);

}

}

boolean hasValueSubList(Node ptr, int v) {

if (ptr.nextNode == null) {

return false; }

else if (ptr.nextNode.value == v) {

return true; }

else {

return hasValueSubList(ptr.nextNode,v);

}

}

}

class Node {

int value;

Node nextNode;

Node(int v, Node n) {

value = v;

nextNode = n;

}

Node (int v) {

this(v,null);

}

}

public class StackWithLinkedList2{

public static void main(String[] args){

int popValue;

Stack myStack = new Stack();

myStack.push(5);

myStack.push(7);

myStack.push(9);

System.out.println(myStack.hasValue(11));

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PROGRAM :

class Stack {
protected Node top;

Stack() {
top = null;
}

boolean isEmpty() {
return (top == null);
}

void push(int v) {
Node tempPointer;
tempPointer = new Node(v);
tempPointer.nextNode = top;
top = tempPointer;
}

int pop() {
int tempValue;
tempValue = top.value;
top = top.nextNode;
return tempValue;
}

void printStack() {
Node aPointer = top;
String tempString = "";
while (aPointer != null) {
tempString = tempString + aPointer.value + "\n";
aPointer = aPointer.nextNode;
}
System.out.println(tempString);
}

boolean hasValue(int v) {
if (top.value == v) {
return true;
} else {
return hasValueSubList(top, v);
}
}

boolean hasValueSubList(Node ptr, int v) {
if (ptr.nextNode == null) {
return false;
} else if (ptr.nextNode.value == v) {
return true;
} else {
return hasValueSubList(ptr.nextNode, v);
}
}

// method to insert a value at the end of the stack
void insertEnd(int v) {
// if stack is empty, adding v as the top node
if (isEmpty()) {
top = new Node(v);
} else {
// else, calling the private recursive method, passing top node and
// v
insertEnd(top, v);
}
}

// private helper method to assist the above method. this is where the
// actual recursion takes place
private void insertEnd(Node n, int v) {
// if n is the last node (no next node), adding a new node after n, with
// value v
if (n.nextNode == null) {
n.nextNode = new Node(v);
} else {
// otherwise calling method recursively, passing next node
insertEnd(n.nextNode, v);
}
}
}

class Node {
int value;
Node nextNode;

Node(int v, Node n) {
value = v;
nextNode = n;
}

Node(int v) {
this(v, null);
}
}

public class StackWithLinkedList2 {
public static void main(String[] args) {
int popValue;
Stack myStack = new Stack();
myStack.push(5);
myStack.push(7);
myStack.push(9);
// printing stack
myStack.printStack();
// adding 11 to the end
myStack.insertEnd(11);
// printing stack again
myStack.printStack();
}
}

OUTPUT :

9
7
5

9
7
5
11

Add a comment
Know the answer?
Add Answer to:
JAVA language Add a recursive method to the program shown in the previous section that states...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test...

    JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test it is not executing but my stack is working fine, can you fix it please! MyQueue.java Implement a queue using the MyStack.java implementation as your data structure.  In other words, your instance variable to hold the queue items will be a MyStack class. enqueue(String item): inserts item into the queue dequeue(): returns and deletes the first element in the queue isEmpty(): returns true or false...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)   ...

    Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)    at InfixExpression.Evaluate(InfixExpression.java:65)    at InfixExpression.setWholeExpr(InfixExpression.java:24)    at InfixExpression.<init>(InfixExpression.java:17)    at Main.testHW1(Main.java:17)    at Main.main(Main.java:6)" I need to get this as my output: "Testing InfixExpression: When passing null, the String and double = Infix String: , result: 0.0 When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805 ..." I...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how...

    Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how to get size. I'm not sure. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null; prev = null; data = 0; } /* Constructor */ public Node(int d, Node n, Node p) { data = d; next = n; prev = p; } /* Function...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT