Skip to content

Instantly share code, notes, and snippets.

@spininertia
Last active December 14, 2015 18:08
Show Gist options
  • Save spininertia/5126811 to your computer and use it in GitHub Desktop.
Save spininertia/5126811 to your computer and use it in GitHub Desktop.
package chapter3;
import java.util.Stack;
/*
* Career Cup 3.6
*
* Write a program to sort a stack in ascending order (with biggest items on top).
* You may use additional stacks to hold items, but you may not copy the elements into any other data structure
* (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty.
*/
public class C3P6 {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
public C3P6(int array[]){
for (int i = 0; i < array.length; i++) {
s1.push(array[i]);
}
}
public void sort(){
while(!s1.isEmpty()){
int data = s1.pop();
while(!s2.isEmpty() && s2.peek() < data){
s1.push(s2.pop());
}
s2.push(data);
}
while(!s2.isEmpty()) {
s1.push(s2.pop());
}
}
public static void main(String[] args) {
int array[] = {2, 4, 9, 3, 7};
C3P6 problem = new C3P6(array);
System.out.println(problem.s1);
problem.sort();
System.out.println(problem.s1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment