How to sort a stack using only stack operations?

2019-01-21 01:35发布

I found this question on the web.

Given a stack S, write a C program to sort the stack (in the ascending order). We are not allowed to make any assumptions about how the stack is implemented. The only functions to be used are:

Push
Pop
Top
IsEmpty
IsFull

I think we can build heap and sort it. What is optimal solution to this?

13条回答
可以哭但决不认输i
2楼-- · 2019-01-21 02:39

Here is the solution in Javascript based on the answer given by @OrenD

var org = [4,67,2,9,5,11,3];
var helper = [];

while(org.length > 0){
    var temp = org.pop();
    while((helper.length > 0) && (helper[helper.length-1] < temp)){
        org.push(helper.pop());
    }
    helper.push(temp);
}

while(helper.length > 0){
    org.push(helper.pop());
}
查看更多
登录 后发表回答