sweet1cris

Untitled

Nov 22nd, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param stack an integer stack
  4.      * @return void
  5.      */
  6.     public void stackSorting(Stack<Integer> stack) {
  7.         // Write your code here
  8.         Stack<Integer> tmp = new Stack<Integer>();
  9.         while (!stack.isEmpty()) {
  10.             if (!stack.isEmpty() && (tmp.isEmpty() || tmp.peek() >= stack.peek())) {
  11.                 tmp.push(stack.peek());
  12.                 stack.pop();
  13.             }
  14.             else {
  15.                 int value = stack.peek(); stack.pop();
  16.                 while (!tmp.isEmpty() && tmp.peek() <= value)  {
  17.                     stack.push(tmp.peek());
  18.                     tmp.pop();
  19.                 }
  20.                 stack.push(value);
  21.                 while (!tmp.isEmpty()) {
  22.                     stack.push(tmp.peek());
  23.                     tmp.pop();
  24.                 }
  25.             }
  26.         }
  27.         while (!tmp.isEmpty()) {
  28.             stack.push(tmp.peek());
  29.             tmp.pop();
  30.         }
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment