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

前端 未结 10 2039
爱一瞬间的悲伤
爱一瞬间的悲伤 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:05

    What temporary data structures can you use? With push and pop, and no temporary storage for n elements, accessing data near the bottom of the stack would be impossible without storing the rest -somewhere-.

    If top (equiv to {x=pop();push(x);return x}) was replaced with shift, it would be perfectly doable - the stack would change into fifo (shift+push; pop would fall into disuse) and it would allow for an easy bubblesort on currently available elements.

提交回复
热议问题