Question

In each plastic container of Pez candy, the colors are stored in random order. Your little...

In each plastic container of Pez candy, the colors are stored in random order. Your little brother likes only the yellow ones, so he painstakingly takes out all the candies, one by one, eats the yellow ones, and keeps the others in order, so that he can return them to the container in exactly the same order as before - minus the yellow candies, of course. Write the algorithm to simulate this process. You may use any of stack operations (Describe your Algorithm)

Homework Answers

Answer #1

#include <bits/stdc++.h>
using namespace std;


int main() {
  stack<char>s1, s2;
  //R=RED, B=BLUE, Y=YELLOW
  s1.push('R');
  s1.push('B');
  s1.push('Y');
  s1.push('R');
  s1.push('Y');
  s1.push('B');
  s1.push('Y');

  //AFTER PUSH OPERATION STACK S1 will be like
//   Yellow => Top of Stack S1
//   Blue
//   Yellow
//   Red
//   Yellow
//   Blue
//   Red    => Bottom of Stack S1


// Process 1 => Popping elements from S1 and Storing all elements other then Yellow to  ///Stack S2


  while(!s1.empty()){
      if(s1.top()!='Y'){
          s2.push(s1.top());
      }
      s1.pop();
  }

  //AFTER ABOVE OPERATION STACK S2 will be like :
//   Red
//   Blue 
//   Red
//   Blue


// Reversing order of Stack S2 and Storing Elements in Stack S1

  while(!s2.empty()){
      s1.push(s2.top());
      s2.pop();
  }

//   Displaying Elements of Stack S1 after removing all Yellow Candies.

  while(!s1.empty()){
      if(s1.top()=='R')cout<<"RED"<<endl;
      if(s1.top()=='B')cout<<"BLUE"<<endl;
      if(s1.top()=='Y')cout<<"YELLOW"<<endl;
      s1.pop();
  }
  return 0;
}

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
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT