Question

In: Computer Science

Java Language Add a recursive method to the program shown in the previous section that allows...

Java Language

Add a recursive method to the program shown in the previous section that allows remove the last node from 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));

}

}

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

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

Solutions

Expert Solution

Concept to Solve the problem of deleting the last node:

  • Make the node (Second last node pointing to last node) point to null.
  • then the Second last node will become the last node

Description:

The method to remove the last node from the stack is given below:

/**
         * This method will delete the last node from the stack
         * @param head : Starting of the head
         * @return : head of  the new list
         */
        public Node delete( Node head )
        {
                Node solution, smallerSol;

                /*** ============================
              Handle Base cases
              ============================ ***/
                
                /**Check if the head is null**/
                if ( head == null )           /**Base case 1**/
                {
                        solution = null;

                        return solution;
                }
                /**check if node's next node is null*/
                else if ( head.nextNode == null )  /** Base case 2**/
                {
                        solution = null;

                        return solution;
                }
                else
                {
                        /** =================================================
                   Assume that the list is not empty...
                    And "head.next" points to a SHORTER list !
                    ================================================= **/

                        /**
                         * recursive call to delete method
                         */
                        smallerSol = delete( head.nextNode ); /** Have someone else delete the last**/      
                        /** node in a SHORTER list and return
                         back the new list**/

                        head.nextNode = smallerSol;    /** Solve problem with smaller solution**/

                        solution = head;           /** Solution = list starting at head**/

                        return solution;           /** Return the head of the new list**/
                } 
        }

Complete Class:

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);

                }

        }

        /**
         * This method will delete the last node from the stack
         * @param head : Starting of the head
         * @return : head of  the new list
         */
        public Node delete( Node head )
        {
                Node solution, smallerSol;

                /*** ============================
              Handle Base cases
              ============================ ***/
                
                /**Check if the head is null**/
                if ( head == null )           /**Base case 1**/
                {
                        solution = null;

                        return solution;
                }
                /**check if node's next node is null*/
                else if ( head.nextNode == null )  /** Base case 2**/
                {
                        solution = null;

                        return solution;
                }
                else
                {
                        /** =================================================
                   Assume that the list is not empty...
                    And "head.next" points to a SHORTER list !
                    ================================================= **/

                        /**
                         * recursive call to delete method
                         */
                        smallerSol = delete( head.nextNode ); /** Have someone else delete the last**/      
                        /** node in a SHORTER list and return
                         back the new list**/

                        head.nextNode = smallerSol;    /** Solve problem with smaller solution**/

                        solution = head;           /** Solution = list starting at head**/

                        return solution;           /** Return the head of the new list**/
                } 
        }

}

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();
                
                /** Add to stack */

                myStack.push(5);

                myStack.push(7);

                myStack.push(9);

                myStack.push(19);

                myStack.push(91);

                myStack.push(93);

                myStack.push(10);

                myStack.push(20);

                System.out.println("check if stack has value 11");
                System.out.println(myStack.hasValue(11));

                System.out.println("Print the stack");
                myStack.printStack();

                System.out.println("delete the last node from stack");
                myStack.delete(myStack.top);

                System.out.println("print the stack again");
                myStack.printStack();
                
                System.out.println("Push another item to stack");
                
                myStack.push(100);
                
                System.out.println("Print the stack again");
                myStack.printStack();

                System.out.println("delete the last node from stack");
                myStack.delete(myStack.top);

                System.out.println("Print the stack again");
                myStack.printStack();
        }

}

Console output of working of delete method to remove the last node:


Related Solutions

Java Language Add a recursive method to the program shown in the previous section that allows...
Java Language Add a recursive method to the program shown in the previous section that allows insert a value at the end of 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() {...
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 nodes does the stack have. 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...
Java program Statement: Provide a user interface to the invoice program in Section 12.3 that allows...
Java program Statement: Provide a user interface to the invoice program in Section 12.3 that allows a user to enter and print an arbitrary invoice. Do not modify any of the existing classes. ..... ..... ..... /** Describes an invoice for a set of purchased products. */ public class Invoice { /** Adds a charge for a product to this invoice. @param aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Product...
Complete java program below. Complete non-recursive version nthFibonacciWithLoop() method. Complete recursive version nthFibonacciWithRecursion() method. public class...
Complete java program below. Complete non-recursive version nthFibonacciWithLoop() method. Complete recursive version nthFibonacciWithRecursion() method. public class Fibonacci { // Fib(N): N N = 0 or N = 1 // Fib(N-1) + Fib(N-2) N > 1 // For example, // Fib(0) = 0 // Fib(1) = 1 // Fib(2) = Fib(1) + Fib(0) = 1 + 0 = 1 // Fib(3) = Fib(2) + Fib(1) = Fib(2) + 1 = (Fib(1) + Fib(0)) + 1 = 1 + 0 + 1...
java Write a recursive program to reverse a positive integer. . Your method should take a...
java Write a recursive program to reverse a positive integer. . Your method should take a non negative integer as a parameter and return the reverse of the number as an integer. e.g. if you pass 12345, your method should return 54321.
Please use java language Thanks! Implement a recursive method called "pow" that takes 2 integers, x...
Please use java language Thanks! Implement a recursive method called "pow" that takes 2 integers, x and y, as parameters and returns the value xy (x raised to the power y). The exponent must be non-negative. If a negative argument is given for the exponent, then an exception should be thrown. Implement a recursive method called "fib" that takes a positive integer, n, as a parameter and returns the nth Fibonacci value. Assume that the first 2 values in the...
Language: Java Create a TryIt.java program with a main method. You are going to use this...
Language: Java Create a TryIt.java program with a main method. You are going to use this program to demonstrate some things about how Java works. Make your methods here private, because they are not intended to be called from outside the program. For each test below, make sure that you print to the console: 1) What is being tested 2) The desired output 3) The actual output Question to be answered: Should you use == or the String method equals...
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is...
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is similar to binary search, except it tries to begin the search nearer to the location of the item. Instead of the using the middle value of the sorted array, interpolation search estimates the location of the target with respect to the first & last values in the array. The implementation is the same as binary search except that you should calculate the mid value...
There is a Java program that is missing one recursive function: public class Ackermann { /*...
There is a Java program that is missing one recursive function: public class Ackermann { /* / n+1 when m = 0 * ack(m,n) = | ack(m-1,1) when m > 0 and n = 0 * \ ack(m-1, ack(m, n-1)) otherwise */ public static int ack(int m, int n) { return 0; } /* Ackermann's Function Test Framework * * Be extremely careful with these test cases. Ackermann's grows very fast. * For example, ack(4, 0) = 13, but ack(5,0)...
There is a Java program that is missing one recursive function: public class BinarySearch { /*...
There is a Java program that is missing one recursive function: public class BinarySearch { /* / -1 when min > max * | mid when A[mid] = v * search(A, v, min, max) = | search(A,v,mid+1,max) when A[mid] < v * \ search(A,v,min,mid-1) otherwise * where mid = (min+max)/2 */ public static int search_rec(int[] A, int v, int min, int max) { return 0; } public static int search(int[] A, int v) { return search_rec(A, v, 0, A.length-1); }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT