一个栈实现排序

用一个栈实现把栈内元素从大到小排序栈顶元素是最大的
只能使用栈这种结构不能使用其他结构;
题解:
首先设置一个辅助栈:
假设原来栈里的元素是1,5,2,4,6,3;
辅助栈:先判断辅助栈栈顶元素是不是比栈顶元素大,是直接加不管,不是则将辅助栈元素弹出加入原栈中重新入栈即可;
代码实现:
public class DAXIAO {

public static void Reve(Stack<Integer> stack)
{
    Stack<Integer>stack1=new Stack<>();
    while(!stack.isEmpty())
    {
        int cur=stack.pop();
        while(!stack1.isEmpty()&&stack1.peek()<cur)
        {
            stack.push(stack1.pop());
        }
        stack1.push(cur);
    }
    while(!stack1.isEmpty())
    {
        stack.push(stack1.pop());
    }

}
    public static void main(String [] args)
    {
    Stack<Integer> stack=new Stack<Integer>();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    Reve(stack);
    while(!stack.isEmpty())
    System.out.println(stack.pop());
    }
}
全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
03-13 10:56
点赞 评论 收藏
转发
头像
04-26 15:00
已编辑
算法工程师
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务