How to sort a stack using only Push, Pop, Top, IsEmpty, IsFull?

前端 未结 10 1968
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-06 09:26

Given a stack S, need to sort the stack using only Push, Pop, Top, IsEmpty, IsFull.

Looking for most sim

10条回答
  •  有刺的猬
    2021-02-06 10:03

    Its not possible.

    That happens because you cant iterate through the stack, because it has to be in place (you could if you would use extra memory). So if you cant iterate through the stack you cant even compare two elements of the stack. A sort without comparing would need extra memory, so that cant be used either.

    Also im sure its not homework, because i dont think a teacher would give you a problem that cant be solved.

    If you really have to do it only with stacks, just use 1-2 extra temporary stacks (i think 2 are needed, but not 100% sure) and do it.

提交回复
热议问题