双栈排序

<pre name="code" class="java">package com.mianshi;
 
import java.util.ArrayList;
import java.util.Stack;
 
public class jingdian_16 {
 
    public static void main(String[] args) {
        int[] numbers =new int[]{2,1,5,3,4};
        ArrayList<Integer> list =jingdian_16.twoStacksSort(numbers);
        for(int i=0;i<list.size();i++){
            System.out.print(list.get(i)+" ");
        }
 
    }
    public static ArrayList<Integer> twoStacksSort(int[] numbers) {
        //栈1存储数据
        Stack<Integer>  stack1 =new Stack<Integer>();
        //栈2临时存储
        Stack<Integer>  stack2 =new Stack<Integer>();
        ArrayList<Integer> list =new ArrayList<Integer>();
        
        for(int i=0;i<numbers.length;i++){
                 stack1.push(numbers[i]);    
        }
        //isEmpty()判断是否为空,是空返回true,不是返回false
        while(!stack1.isEmpty()){
            //stack1中最上边的元素出栈
               int a =stack1.pop();
               //判断stack2中是否已经有数据,并且如果里面顶上的数据大于stack1中刚弹出的a,则需要换位置
               //stack2.peek()表示得到栈顶的值但不需要弹出
               while(!stack2.isEmpty() && stack2.peek()>a){
                      //如果成立则有,将stack2中的栈顶数据弹出放到stack1
                   stack1.push(stack2.pop());
                   //继续循环判断是否还有符合条件的
               }
               //循环之后就需要将stack1弹出的数据放到stack2中
               stack2.push(a);
        }
        //遍历输出
        while(!stack2.isEmpty()){
            list.add(stack2.pop());
        }
         return list;        
    }
 
}

 

posted @ 2021-03-02 19:42  lzk_seven  阅读(106)  评论(0编辑  收藏  举报