Stack Sorting 229

Question

Sort a stack in ascending order (with biggest terms 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 (e.g. array).

Example

Given stack =

| |

|3|

|1|

|2|

|4|

return:

| |

|4|

|3|

|2|

|1|

The data will be serialized to [4,2,1,3]. The last element is the element on the top of the stack.

Solution

我的思路:

1) 用count记录已经排好序的元素个数,则stack.size()-count为未排序元素个数,每次将栈顶stack.size()-count个元素出栈

2) 将stack中全部出栈元素倒到helper stack中时寻找其中的最小者,将其加入回stack

3) 将helper stack中非最小值的元素倒回stack中

时间复杂度O(n^2),空间复杂度O(n)

另一种方法:

1) 从origin stack中不断pop() element

2) 对于helper stack,如果helper stack peek() < element,则将helper stack中的元素全部转移到origin stack

3) 再将element push()到helper stack中

4) 不断重复上述步骤,直到origin stack isEmpty

5) 最后,所有的元素已经按照descending order排序好(smallest on top),只需将其转移到origin stack,则origin stack即为所需排序

时间复杂度和空间复杂度均与第一种相同。

代码如下:

第一种:

private void stackSorting(Stack<Integer> stack){
        Stack<Integer> stack2 = new Stack<Integer>();

        int count = 0;

        while(stack.size() - count > 0){
            int numberLeft = stack.size() - count;
            int min = Integer.MAX_VALUE;
            while(numberLeft > 0){
                int curt = stack.pop();
                min = Math.min(min, curt);
                stack2.push(curt);
                numberLeft--;
            }
            stack.push(min);
            while(!stack2.isEmpty()){
                int curt = stack2.pop();
                if(curt != min){
                    stack.push(curt);
                }
            }
            count++;
        }
    }
第二种:

```
public void stackSorting(Stack<Integer> stack) {
    Stack<Integer> helpStack = new Stack<Integer>();
    while (!stack.isEmpty()) {
        int element = stack.pop();
        while (!helpStack.isEmpty() && helpStack.peek() < element) {
            stack.push(helpStack.pop());
        }
        helpStack.push(element);
    }
    while (!helpStack.isEmpty()) {
        stack.push(helpStack.pop());
    }
}
```

results matching ""

    No results matching ""