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

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

    It can be done...


    Ok: sorted, ahem, "in-place" with only the listed ops, didn't need Top() or IsFull() or another stack or data structure other than the call frames. (Presumably the whole point of the homework problem was to require a recursive solution.)

    Ruby

    @a = [3, 2, 1, 6, 5, 4]
    
    class Array
      def empty?
        return size == 0
      end
    end
    
    def sort e
      if @a.empty?
        @a.push e
        return
      end
      t = @a.pop
      if e > t
        @a.push(t).push(e)
        return
      end
      sort e
      @a.push t
    end
    
    def resort
      return if @a.empty?
      t = @a.pop
      resort
      sort t
    end
    
    p ['first ', @a]
    resort
    p ['final ', @a]
    

提交回复
热议问题