Question

Write a recursive method to print the last value in a stack Write a recursive method...

  1. Write a recursive method to print the last value in a stack
  2. Write a recursive method to reverse the contents of a queue

*java IDE

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

Dear student, according to the question, the resultant programs are as follows:

Recursive method to Print the Last Value in Stack:

/* Java program to print last value in the stack */
class Stack
{
   static final int SIZE = 10;
   int top;
int a[] = new int[SIZE]; // Maximum size of Stack

Stack() // default constructor to initialize top value
   {
       top = -1;
   }

   void push(int x) // to push value onto stack
   {
       if (top >= (SIZE-1))
       {
           System.out.println("Stack Overflow");
       }
       else
       {
           a[++top] = x;
           System.out.println("element "+ x + " pushed into stack");
       }
   }

   int pop()
   {
       if (top < 0)
       {
           System.out.println("Stack Underflow");
           return 0;
       }
       else
       {
           int x = a[top--];
           return x;
       }
   }
int lastValueInStack(int top) // considering top vaue to get the last value
{
int r;
if(top == 0) // the last value has been stored onto stack at top = 0.
return pop();
else
r = pop();
return lastValueInStack(top-1); // So keep on recursivelly calling till we get top value as 0
}
}

// Main code
class Main
{
   public static void main(String args[])
   {
       Stack s = new Stack();
s.push(1);
       s.push(10);
       s.push(20);
       s.push(30);
   System.out.println(s.lastValueInStack(s.top) + " is the last value from stack");
  
   }
}

Output:

Add a comment
Know the answer?
Add Answer to:
Write a recursive method to print the last value in a stack Write a recursive method...
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
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