1 public class Solution {
 2   public void sort(LinkedList<Integer> stack1) {
 3          LinkedList<Integer> stack2 = new LinkedList<Integer>();
 4       int min = Integer.MAX_VALUE;
 5       int counter = 0;
 6       int size2 = 0;
 7 
 8       while (stack1.size() > 0) {
 9         while (!stack1.isEmpty()) {
10           int top = stack1.pop();
11           if (top == min) {
12             counter++;
13             continue;
14           } else if (top < min) {
15             for (int m = 1; m <= counter; m++) {
16               stack2.push(min);            // Re-add previous smallest number to stack2
17             }
18             min = top;                        //Reset counter and min
19             counter = 1;
20           } else {
21             stack2.push(top);
22           }
23         }
24 
25         while (!stack2.isEmpty() && stack2.size() > size2) {     // shuffle elements from stack2 back to stack1;
26           stack1.push(stack2.pop());
27         }
28 
29         for (int j = 1; j <= counter; j++) {
30           stack2.push(min);
31         }
32         min = Integer.MAX_VALUE;
33         size2 = stack2.size();
34         counter = 0;            // <-- 忘记重新初始化了!!!!!
35       }
36 
37       while(!stack2.isEmpty()) {
38         stack1.push(stack2.pop());
39       }
40   }
41 }

 

posted on 2018-03-19 02:24  mayinmiao  阅读(144)  评论(0编辑  收藏  举报