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

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

    For this problem, can we consider using system stack? Make several recursive calls.

    public static void sort(Stack<Integer> s) {
        if (!s.isEmpty()) {
            Integer t = s.pop();
            sort(s);
            insert(t, s);
        }
    }
    
    private static void insert(Integer x, Stack<Integer> s) {
        if (s.isEmpty()) {
            s.push(x);
            return;
        }
    
        if (x < s.peek()) {
            Integer t = s.pop();
            insert(x, s);
            s.push(t);
        } else {
            s.push(x);
        }
    }
    
    0 讨论(0)
  • 2021-02-06 09:51

    You can't. You can't reorder the contents of a stack without removing elements, by definition. Also push and pop aren't in-place operations, so basically you're asking to sort a stack with Top, IsEmpty and IsFull. IsEmpty = !IsFull. So you're asking to sort a stack with Top and IsEmpty.

    0 讨论(0)
  • 2021-02-06 09:56

    To bad you couldn't have two other stacks, then you could have played the Towers of Hanoi in O(n) space.

    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-06 10:04

    techInterview Discussion - Sorting on Stack

    More pseudo than anything, but there is code examples and possible solution.

    0 讨论(0)
提交回复
热议问题