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

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

    Bubble Sort and Insert Sort in Java https://github.com/BruceZu/sawdust/blob/82ef4729ee9d2de50fdceab2c8976d00f2fd3ba0/dataStructuresAndAlgorithms/src/main/java/stack/SortStack.java

     /**
      * Sort the stack using only Stack API, without using other data structure
      * Ascending from bottom to top
     */
    public class SortStack> {
     int sorted;
    
    /**
     * Just Bubble Sort.
     */
    private void bubble(Stack s, T max) {
        if (s.empty() || s.size() == sorted) {
            s.push(max);
            sorted++;
            return; // note return
        }
    
        T currentTop = s.pop();
        if (max.compareTo(currentTop) < 0) {
            T tmp = max;
            max = currentTop;
            currentTop = tmp;
        }
    
        bubble(s, max);
        s.push(currentTop);
    }
    
    public Stack sortAscending(Stack s) {
        sorted = 0;
        if (s == null || s.size() <= 1) {
            return s;
        }
    
        while (sorted != s.size()) {
            bubble(s, s.pop());
        }
        return s;
    }
    
    /**
     * Just Insert Sort.
     */
    private void insertSort(Stack s) {
        if (s.empty()) {
            return;
        }
        T currentTop = s.pop();
        insertSort(s);
        insert(s, currentTop);
    }
    
    private void insert(Stack s, T insert) {
        if (s.isEmpty() || insert.compareTo(s.peek()) <= 0) {
            s.push(insert);
            return;
        }
    
        T current = s.pop();
        insert(s, insert);
        s.push(current);
    }
    
    public Stack sortAscendingByInsertSort(Stack s) {
        if (s == null || s.size() <= 1) {
            return s;
        }
        insertSort(s);
        return s;
     }
    }
    

提交回复
热议问题