Friday, 12 February 2016

Reverse stack using pop/push

package exercises;

import java.util.ArrayList;
import java.util.Stack;
import java.util.function.Consumer;

public class MyStack {
private Stack ints = new Stack<>();
public void add(int item) {
ints.push(item);
}
public void printall() {
ArrayList array = new ArrayList<>(ints);
array.forEach(new Consumer() {
@Override
public void accept(Integer t) {
System.out.print(t + "-->");
}
});
System.out.print("\n");
}
public void reverse_easy() {
Stack other = new Stack<>();
while(!ints.isEmpty()) {
other.push(ints.pop());
}
ints = other;
}
/**
* reverse relies on double recursion
* Outer Recursion : Pop all items
* Inner Recursion : Adds item at the bottom.
*/
public void reverse() {
this.reverse(this.ints);
}
private void reverse(Stack stack) {
Integer item = stack.pop();
if(!stack.isEmpty()) reverse(stack);
this.insertAtBottom(stack, item);
}
private void insertAtBottom(Stack stack, Integer item) {
if(stack.isEmpty()) {
stack.push(item);
} else {
Integer top = stack.pop();
insertAtBottom(stack, item);
stack.push(top);
}
}

}

No comments: