数据结构 给定一个整数堆栈,使用另一个临时堆栈按升序对其进行排序。

例子: 

Input : [34, 3, 31, 98, 92, 23]
Output : [3, 23, 31, 34, 92, 98]

Input : [3, 5, 1, 4, 2, 8]
Output : [1, 2, 3, 4, 5, 8] 

算法:

  1. 创建一个临时堆栈,比如 tmpStack
  2. 当输入堆栈不为空时,请执行以下操作:
    • 从输入堆栈中弹出一个元素,称之为 temp
    • 当临时堆栈不为空且临时堆栈顶部大于 temp 时,
      从临时堆栈弹出并将其推送到输入堆栈
    • 在临时堆栈中推送temp

import java.util.*;
 
class SortStack
{
        public static Stack<Integer> sortstack(Stack<Integer>
                                             input)
    {
        Stack<Integer> tmpStack = new Stack<Integer>();
        while(!input.isEmpty())
        {
            //创建一个临时栈
            int tmp = input.pop();
         
            //如果临时栈不为空且临时栈顶元素大于输入栈顶元素,则将临时栈顶的元素存入到输入栈
            while(!tmpStack.isEmpty() && tmpStack.peek()
                                                 > tmp)
            {
                
            input.push(tmpStack.pop());
            }
             
            
            tmpStack.push(tmp);
        }
        return tmpStack;
    }
     
   
    public static void main(String args[])
    {
        Stack<Integer> input = new Stack<Integer>();
        input.add(34);
        input.add(3);
        input.add(31);
        input.add(98);
        input.add(92);
        input.add(23);
     
       
        Stack<Integer> tmpStack=sortstack(input);
        System.out.println("Sorted numbers are:");
     
        while (!tmpStack.empty())
        {
            System.out.print(tmpStack.pop()+" ");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值