You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中使用Stack实现排序故障:输出未有序,求解决方法

如何用栈实现元素排序并输出有序结果

嘿,我发现你当前的代码只是把输入的数字直接推入栈中,然后直接弹出打印——这只会得到输入的逆序结果,因为栈本身是「后进先出(LIFO)」的结构,它并不会自动帮你排序元素。要实现你想要的有序输出,我们需要额外的逻辑来借助栈完成排序操作。

问题分析

你现在的代码逻辑是:输入n个数字→全部推入栈→依次弹出打印。比如你输入10、5、20,栈内的存储顺序是[10,5,20](10在栈底,20在栈顶),弹出时会先输出20,再5,最后10,和你期望的5 10 20完全相反。

解决方案:用辅助栈实现排序

我们可以引入一个辅助栈来存放已经排好序的元素,核心逻辑步骤如下:

  • 从原栈弹出一个元素
  • 将辅助栈中所有比当前元素大的元素移回原栈
  • 将当前元素推入辅助栈
  • 重复上述步骤直到原栈为空,此时辅助栈内的元素就是升序排列的(栈底是最小元素,栈顶是最大元素)
  • 最后依次弹出辅助栈的元素,就能得到从小到大的有序输出

修正后的完整代码

import java.util.Scanner;
import java.util.Stack;

public class SortedStackDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the size of stack: ");
        int stackSize = scanner.nextInt();
        
        Stack<Integer> originalStack = new Stack<>();
        // 输入元素到原栈
        for (int i = 0; i < stackSize; i++) {
            System.out.printf("Enter the %s Number: ", getOrdinal(i + 1));
            int number = scanner.nextInt();
            originalStack.push(number);
            System.out.println("The Number is entered in the stack.");
        }
        
        // 用辅助栈排序
        Stack<Integer> tempStack = new Stack<>();
        while (!originalStack.isEmpty()) {
            int current = originalStack.pop();
            // 将辅助栈中比current大的元素移回原栈
            while (!tempStack.isEmpty() && tempStack.peek() > current) {
                originalStack.push(tempStack.pop());
            }
            tempStack.push(current);
        }
        
        // 输出有序结果
        System.out.println("\nOutput:");
        while (!tempStack.isEmpty()) {
            System.out.print(tempStack.pop() + " ");
        }
        
        scanner.close();
    }
    
    // 辅助方法:生成序数词(1st, 2nd, 3rd...)
    private static String getOrdinal(int num) {
        if (num >= 11 && num <= 13) {
            return num + "th";
        }
        switch (num % 10) {
            case 1: return num + "st";
            case 2: return num + "nd";
            case 3: return num + "rd";
            default: return num + "th";
        }
    }
}

测试示例

输入:

Enter the size of stack: 3
Enter the 1st Number: 10
The Number is entered in the stack.
Enter the 2nd Number: 5
The Number is entered in the stack.
Enter the 3rd Number: 20
The Number is entered in the stack.

输出:

Output:
5 10 20 

这样就能完美实现你想要的有序输出啦~

内容的提问来源于stack exchange,提问作者oman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:46:05