Skip to content

Instantly share code, notes, and snippets.

@XiaoxiaoLi
Created July 5, 2014 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XiaoxiaoLi/34f1cdc635f1365a9f70 to your computer and use it in GitHub Desktop.
Save XiaoxiaoLi/34f1cdc635f1365a9f70 to your computer and use it in GitHub Desktop.
#CC150 #CC150-chap3 3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack 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.
//3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack 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 StackSorter{
// Variation of Insertion Sort by using an extra stack. Iterate through every item in the input stack
// We need to find the right place to insert the item in the result stack
// we need to pop every item that is larger than it and we can store them by pushing them in the input stack, and then we push the element in the result stack
// Time: O(n^2), Space O(n)
public static Stack<Integer> sortStackAscWithOneExtraStack(Stack<Integer> s){
Stack<Integer> r = new Stack<Integer>();
while(!s.empty()){
// Take each element out, store in a temporaty variable
int tmp = s.pop();
// Insert the element in the right place in the result stack
// pop the larger items and store them in the original stack
while(!r.empty() && r.peek()>tmp){
s.push(r.pop());
}
// insert the tmp element to the result stack, it is the largest in the result stack.
r.push(tmp);
}
return r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment