Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

In java create this method with name Mirror, that accepts a stack of integers as a parameter and replaces the stack contents with itself plus

In java create this method with name Mirror, that accepts a stack of integers as a parameter and replaces the stack contents with itself plus a mirrored version of itself (the same elements in the opposite order). For example, if the stack stores [10, 23, 19, 44], your method should change the stack to store [10, 23, 19, 44, 44, 19, 23, 10]. If passed an empty stack, your result should be an empty stack.

My code is below but the output of my order is coming up as [9,7,5,3,1,1,3,5,7,9] and it needs to be [1,3,5,7,9,9,7,5,3,1] how do i fix this issue

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

public class numberOne { public static void main(String[] args){ Stack stack1 = new Stack(); stack1.push(1); stack1.push(3); stack1.push(5); stack1.push(7); stack1.push(9); System.out.println(stack1); stack1 = mirror(stack1); System.out.println("Mirrored stack: " + stack1); Stack stack2 = new Stack(); stack2.push(12); stack2.push(24); stack2.push(36); stack2.push(48); stack2.push(60); System.out.println(stack2); stack2 = mirror(stack2); System.out.println("Mirrored stack: " + stack2); } public static Stack mirror(Stackstack){ if(stack==null) return null; Stack s = new Stack(); Queue queue = new LinkedList(); while(!stack.isEmpty()){ int val = stack.peek(); queue.add(val); s.push(val); stack.pop(); } while(!queue.isEmpty()){ int val = queue.poll(); stack.push(val); } while(!s.isEmpty()){ int val = s.peek(); stack.push(val); s.pop(); } return stack; } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle Database Administration The Essential Reference

Authors: Brian Laskey, David Kreines

1st Edition

1565925165, 978-1565925168

More Books

Students also viewed these Databases questions