Question

Suppose you have a stack S containing n elements and a queue Q that is initially...

Suppose you have a stack S containing n elements and a queue Q that is initially empty. Write a program in which you can use Q to scan S to see if it contains a certain element x, with the additional constraint that your algorithm must return the elements back to S in their original order. You may only use S, Q, and a constant number of other primitive variables

Homework Answers

Answer #1

JAVA PROGRAM

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class StackQueue {
  
   public static void main(String[] args){
      
       //instantiate a stack of Integers S
       Stack<Integer> S = new Stack<Integer>();
       final int n = 10; //define n as 10
      
       //push 10 random integers into S
       //random integers can be anything between 0 to 25(exclusive)
       for(int i = 1; i <= n; i++){
           S.push((int)(Math.random()*25));
       }
       System.out.println("Initial contents of stack (bottom to top):");
       System.out.println(S);
       System.out.println("stack top is="+S.peek());
      
       int x = (int)(Math.random()*25); //x is the element to find in stack
       System.out.println("x (the element to scan) is "+x);
      
       //Instantiate Queue Q
       Queue<Integer> Q = new LinkedList<Integer>();
      
       //run while loop as long as stack is not empty
       while(!S.isEmpty()){
           if(S.peek() == x){//if x is found in Stack
               System.out.println(x+" is Found");//print that it is found
               break;//break out of loop
           }else{
               //otherwise add the stack popped item into queue
               Q.add(S.pop());
           }
       }
      
       if(S.isEmpty()){
           System.out.println(x+" is NOT Found");//print that it is found
       }
      
      
       //reverse the queue elements
       Q = reverseTheQ(Q);
      
       //push the elements from Q into S
       //in original order of S
       while(!Q.isEmpty()){
           S.push(Q.remove());
       }
      
       System.out.println("After scanning the stack now contains: "+S);
       System.out.println("Stack top is =>"+S.peek());  
      
   }
  
   //reverse the contenet s of queue using recusrsion
   private static Queue<Integer> reverseTheQ(Queue<Integer> theQ){
       if(theQ.isEmpty()){//if queue is empty
           return theQ; //the base criteria of the recursion function
       }
      
       int value = theQ.remove();//get and remove the front element of queue
      
       theQ= reverseTheQ(theQ); //now call the reverseTheQ on remaining queue elements
      
       //add the value at rear end of reversed Q
       theQ.add(value);
       //return
       return theQ;
   }

}

=================================

OUTPUT

=================================

RUN1

Initial contents of stack (bottom to top):
[15, 21, 20, 22, 13, 6, 7, 22, 12, 24]
stack top is=24
x (the element to scan) is 1
1 is NOT Found
After scanning the stack now contains: [15, 21, 20, 22, 13, 6, 7, 22, 12, 24]
Stack top is =>24

RUN2

Initial contents of stack (bottom to top):
[8, 8, 15, 1, 2, 11, 11, 18, 14, 20]
stack top is=20
x (the element to scan) is 13
13 is NOT Found
After scanning the stack now contains: [8, 8, 15, 1, 2, 11, 11, 18, 14, 20]
Stack top is =>20

RUN3

Initial contents of stack (bottom to top):
[10, 11, 15, 14, 22, 24, 20, 0, 17, 24]
stack top is=24
x (the element to scan) is 14
14 is Found
After scanning the stack now contains: [10, 11, 15, 14, 22, 24, 20, 0, 17, 24]
Stack top is =>24

please likemy answer THANK YOU!

Know the answer?
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
Similar Questions
TestQueue.java Design a class named Queue for storing integers. Like a stack, a queue holds elements....
TestQueue.java Design a class named Queue for storing integers. Like a stack, a queue holds elements. But in a queue, the elements are retrieved in a first-in first-out fashion. The class contains: An int[] data field named elements that stores the int values in the queue. A data field named size that stores the number of elements in the queue. A constructor that creates a Queue object with default capacity 8. The method enqueue(int v) that adds v into the...
Java Please [(1)] A palindrome is a string that reads the same forwards as backwards. Using...
Java Please [(1)] A palindrome is a string that reads the same forwards as backwards. Using only a fixed number of stacks and queues, the stack and queue ADT functions, and a fixed number of int and char variables, write an algorithm to determine if a string is a palindrome. Assume that the string is read from standard input one character at a time. The algorithm should output true or false as appropriate [(2)] Let Q be a non-empty queue,...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue class . Call your class Queue. it must be a template class. public class Queue { } I have put a driver program in the module . It is called CircularQueue.java This driver program should then run with your Queue class (no modifications allowed to the driver program). Your Queue class should have at least the following methods: one or more constructors, enqueue, dequeue,...
Write a code in c++ using linear insertion following the steps below. Comment your work. 1....
Write a code in c++ using linear insertion following the steps below. Comment your work. 1.    Ask the user for the name of a file containing data. If it does not exist, the program should display an error, then ask for a new file name. Entering an asterisk (*) as the first and only character on a line should terminate the program. 2.     You can use a statically-allocated one-dimensional array of doubles for this with length 100. You...
n this lab, you use what you have learned about parallel arrays to complete a partially...
n this lab, you use what you have learned about parallel arrays to complete a partially completed C++ program. The program should: Either print the name and price for a coffee add-in from the Jumpin’ Jive Coffee Shop Or it should print the message Sorry, we do not carry that. Read the problem description carefully before you begin. The file provided for this lab includes the necessary variable declarations and input statements. You need to write the part of the...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform an empirical analysis of the QuickSort algorithm to study the actual average case behavior and compare it to the mathematically predicted behavior. That is, you will write a program that counts the number of comparisons performed by QuickSort on an array of a given size. You will run the program on a large number of arrays of a certain size and determine the average...
In this project you implement a program such that it simulates the process of repeated attempts...
In this project you implement a program such that it simulates the process of repeated attempts to hit a target with a projectile. The goal is to shoot the projectile within a 1 foot distance from the target, since such a short miss is accepted as a hit. Your program is responsible for the following tasks. Compute the trajectory data of a projectile (such as the time, the maximum height and the distance as described by the formulas above) for...
I've posted this question like 3 times now and I can't seem to find someone that...
I've posted this question like 3 times now and I can't seem to find someone that is able to answer it. Please can someone help me code this? Thank you!! Programming Project #4 – Programmer Jones and the Temple of Gloom Part 1 The stack data structure plays a pivotal role in the design of computer games. Any algorithm that requires the user to retrace their steps is a perfect candidate for using a stack. In this simple game you...
4. Golden Rule. Suppose that we have a standard Solow Model. There is no population or...
4. Golden Rule. Suppose that we have a standard Solow Model. There is no population or technology growth. (a) The rm problem is to maximize prots, t. The rm's problem can be written as: max KtC0;NtC0 t = AK t N1− t − wtNt − rtKt: The rm takes the factor prices as given. Find the rst order conditions characterizing the optimal rm behavior. (b) Use the FONCs from 4a to show that wtNt~Yt = 1 − , where Yt...
Base Conversion One algorithm for converting a base 10 number to another base b involves repeatedly...
Base Conversion One algorithm for converting a base 10 number to another base b involves repeatedly dividing by b. Each time a division is performed the remainder and quotient are saved. At each step, the dividend is the quotient from the preceding step; the divisor is always b. The algorithm stops when the quotient is 0. The number in the new base is the sequence of remainders in reverse order (the last one computed goes first; the first one goes...