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,...
Stack Queue Program Implement a Stack class using the List Class you developed earlier. Test your...
Stack Queue Program Implement a Stack class using the List Class you developed earlier. Test your Stack class by determining if the following strings have matching open and closing ( ) and/or [ ] and/or { }. To test matches, push open (, [, { onto the stack. Input a close char, pop off the stack and see if input matches symbol form stack.   Use the following data to test your code:                               ( )                               [ ] ( )...
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...
You can complete this assignment individually or as a group of two people. In this assignment...
You can complete this assignment individually or as a group of two people. In this assignment you will create a ​​Sorted Singly-Linked List​ that performs basic list operations using C++. This linked list should not allow duplicate elements. Elements of the list should be of type ‘ItemType’. ‘ItemType’ class should have a private integer variable with the name ‘value’. Elements in the linked list should be sorted in the ascending order according to this ‘value’ variable. You should create a...
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...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT