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

前端 未结 10 2024
爱一瞬间的悲伤
爱一瞬间的悲伤 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 s) {
        if (!s.isEmpty()) {
            Integer t = s.pop();
            sort(s);
            insert(t, s);
        }
    }
    
    private static void insert(Integer x, Stack 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);
        }
    }
    

提交回复
热议问题