【刷题 issue5】程序员代码面试指南 —— IT 名企算法与数据结构题目最优解

第一章 栈和队列

1.5 用一个栈实现另一个栈的排序

【题目】

在一个栈中的元素的类型为整形,现在将该栈从顶到底按从大到小的顺序排序,只能申请一个栈。除此之外,可以使用新的变量,但不能使用额外的数据结构。

【难度】

士 ★☆☆☆

【题解】

将要排序的栈记为 stack,申请的辅助栈记为 another。在 stack 上执行 pop 操作,弹出的元素记为 temp:

  • 如果 temp ≤ another 的栈顶元素,则将 temp 直接压入 another;
  • 如果 temp > another 的栈顶元素,则将 another 中的元素逐一弹出压入 stack,直到 temp ≤ another 的栈顶元素,再将 temp 压入 another。

重复执行上述操作,直到 stack 中的全部元素都压入到 another 中。最后将 another 中的所有元素逐一压入 stack 中,即完成排序。这个过程类似于插入排序,但是注意数据结构的局限。

【实现】

  • SortAStack.java
import java.util.Stack;

public class SortAStack {

    private SortAStack() {}

    public static void sortAStackByAnotherStack(Stack<Integer> stack) {
        if (stack == null) {
            throw new RuntimeException("参数不合法!");
        }
        Stack<Integer> another = new Stack<>();
        int temp = 0;
        while (!stack.empty()) {
            temp = stack.pop();
            while (!another.empty() && another.peek() > temp) {
                stack.push(another.pop());
            }
            another.push(temp);
        }
        while (!another.empty()) {
            stack.push(another.pop());
        }
    }

}
  • SortAStackTest.java
import java.util.Iterator;
import java.util.Stack;

public class SortAStackTest {

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.add(2);
        stack.add(3);
        stack.add(1);
        stack.add(5);
        stack.add(4);
        SortAStack.sortAStackByAnotherStack(stack);
        Iterator<Integer> iterator = stack.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

}
发布了147 篇原创文章 · 获赞 72 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Pranuts_/article/details/100162666