Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Stack<T> {
- /** Return true if the collection is empty */
- public boolean isEmpty() { return true; }
- /** Return the top element on the stack */
- public T peek() { return null; }
- /** Return the stack, sans top element */
- public Stack<T> pop() { return this; }
- /** Return a new stack with a given item at the top */
- public Stack<T> push(final T elem) {
- return new Stack<T>() {
- public T peek() { return elem; }
- public Stack<T> pop() { return Stack.this; }
- public boolean isEmpty() { return false; }
- };}
- }
- public static <T extends Comparable<T>> Stack<T> sort(Stack<T> stack) {
- if(stack.isEmpty())
- return;
- T pivot = stack.peek();
- stack = stack.pop();
- Stack<T>
- lt = new Stack<T>(),
- eq = new Stack<T>(),
- gt = new Stack<T>();
- while(!stack.isEmpty()) {
- int comparison = stack.peek().compareTo(pivot);
- if(comparison < 0)
- lt = lt.push(stack.peek());
- else if(comparison > 0)
- gt = gt.push(stack.peek());
- else
- eq = eq.push(stack.peek());
- stack = stack.pop();
- }
- lt = reverse(sort(lt));
- gt = reverse(sort(gt));
- for(;!gt.isEmpty(); gt=gt.pop())
- stack = stack.push(gt.peek());
- for(;!eq.isEmpty(); eq=eq.pop())
- stack = stack.push(eq.peek());
- for(;!lt.isEmpty(); lt=lt.pop())
- stack = stack.push(lt.peek());
- return stack;
- }
- public static Stack<T> reverse(Stack<T> stack) {
- Stack<T> rev = new Stack();
- while(!stack.isEmpty()) {
- rev.push(stack.peek());
- stack = stack.pop();
- }
- return rev;
- }
Advertisement
Add Comment
Please, Sign In to add comment