Question
Program in Netbeans
Write a method Stack Merge (Stack p1, Stack p2) to
0 0
Add a comment Improve this question Transcribed image text
Answer #1


import java.util.Scanner;
import java.util.Stack;


public class StackMerging {

   public static void main(String[] args) {
      
       int count1,count2;
      
       Stack<Integer> p1 = new Stack<Integer>(); // Instance of Stack P1
       Stack<Integer> p2 = new Stack<Integer>(); // Instance of Stack P1
       Stack<Integer> p0 = new Stack<Integer>(); // Instance of Stack P1
      
       Scanner s = new Scanner(System.in);
      
       System.out.println("Enter no. of elements of stack1:");
       count1 = s.nextInt();
      
       System.out.println("Enter no. of elements of stack2:");
       count2 = s.nextInt();
      

      
       System.out.println("Enter elements into stack1:");
       for (int i=0;i<count1;i++) {
           p1.push(s.nextInt()); // Pushing into Stack
       }
      
      
       System.out.println("Enter elements into stack2:");
       for (int i=0;i<count2;i++) {
           p2.push(s.nextInt()); // Pushing into Stack
       }
       System.out.println("Elements of p1 before merging:"+p1);
       System.out.println("Elements of p2 before merging:"+p2);

       p0 = stackMerge(p1,p2); // static method for Merging p1,p2 stacks
      
       System.out.println("Elements of p0 after merging is:"+p0);
      
   }

   private static Stack<Integer> stackMerge(Stack<Integer> p1,
           Stack<Integer> p2) {

       Stack<Integer> p0 = new Stack<Integer>();
      
       int i=0,j=0;
       while(i<p1.size()||j<p2.size()){ // Pushing into Stack P0 by retrieving elements from P1 and P2
           if(i<p1.size()){
               p0.push(p1.get(i));
               i++;
           }
           else{
               if(!p0.contains(p2.get(j))) // Removing duplicates by checking in the P0
                    p0.push(p2.get(j));
               j++;
           }
       }
       return p0;
   }

}

Add a comment
Know the answer?
Add Answer to:
Program in Netbeans Write a method Stack Merge (Stack p1, Stack p2) to return a stack...
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