Brian
Brian

Reputation: 2727

How do you push a recently popped element from one stack to another?

Say I have the following code:

public Stack s1;
public Stack s2;

//I want to take the top element from s1 and push it onto s2

s1.pop();

//Gather recently popped element and assign it a name.

s2.push(recentlyPopped);

Any ideas on how I would do this? Thanks.

Upvotes: 0

Views: 4202

Answers (3)

Drogba
Drogba

Reputation: 4346

Try

String[] inputs = { "A", "B", "C", "D", "E" };
Stack<String> stack1 = new Stack<String>();
Stack<String> stack2 = new Stack<String>();
for (String input : inputs) {
  stack1.push(input);
}
System.out.println("stack1: " + stack1);
System.out.println("stack2: " + stack2);
stack2.push(stack1.pop());
System.out.println("stack1: " + stack1);
System.out.println("stack2: " + stack2);

The output will be:

stack1: [A, B, C, D, E]
stack2: []
stack1: [A, B, C, D]
stack2: [E]

Upvotes: 1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

The basic form would be

s2.push(s1.pop());

If you need to process the data from the 1st stack befor/after pushing it in the 2nd stack, you can use

YourClass yourClass = s1.pop();
//process yourClass variable...
s2.push(yourClass);
//more process to yourClass variable...

Remember to check that s1 isn't empty before using the pop method or else you could get an EmptyStackException.

if (!s1.isEmpty()) {
    s2.push(s1.pop());
}

Upvotes: 3

kosa
kosa

Reputation: 66647

Unless you have other constraints which are not specified in question. One approach would be:

YourElementType elem = s1.pop();

s2.push(elem);

Upvotes: 0

Related Questions