对栈排序

public static void sortStack(Stack stack){
    int temp;
    Stack stack2 = new Stack<>();
    while(!stack.isEmpty()) {
      temp = stack.pop();
      if (stack2.isEmpty()) {
        stack2.push(temp);
      } else { 
     while(!stack2.isEmpty() && stack2.peek() > temp){
         stack.push(stack2.pop());
        }
        stack2.push(temp);
      }
    }
}
比如原来栈中是3,7,2,5,1,则新栈中先加入3,7,此时原栈中取出2时,新栈的3,7,都大于2,所以都取出来,加入到旧的栈中,然后从旧的栈中取出3,7,再加入新栈。
posted @ 2022-10-13 12:05  MarkLeeBYR  阅读(22)  评论(0)    收藏  举报