b_nk_用递归函数和栈逆序一个栈 & 用一个栈实现另一个栈的排序(栈+递归 | 栈)

用递归函数和栈逆序一个栈

实现栈中元素的逆序,但是只能用递归函数来实现,不能用其他数据结构。

思路:这里因为栈的输出本质也是将栈元素逆序,所以我得先将 st1 逆序为 st2,然后将 st2 用递归逆序...

import java.util.*;
import java.io.*;
class Solution {
    int n;
    int getBottom(Stack<Integer> st) {
        int top = st.pop();
        if (st.isEmpty())
            return top;
        int bottom = getBottom(st);
        st.push(top);
        return bottom;
    }
    void reverse(Stack<Integer> st) {
        if (st.isEmpty()) return;
        int e = getBottom(st);
        reverse(st);
        st.push(e);
    }
    void init() throws IOException {
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        Stack<Integer> st1 = new Stack<Integer>(), st2 = new Stack<Integer>();
        n = sc.nextInt();
        for (int i=0; i<n; i++) st1.push(sc.nextInt());
        while (!st1.isEmpty()) st2.push(st1.pop());
        reverse(st2);
        while (!st2.isEmpty()) {
            System.out.print(st2.pop()+" ");
        }
    }
}
public class Main{
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
        s.init();
    }
}

用一个栈实现另一个栈的排序

输入
5
5 8 4 3 6
输出
8 6 5 4 3
import java.util.*;
import java.math.*;
import java.io.*;
class Solution {
    void init() throws IOException {
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        Stack<Integer> data = new Stack<>(), st = new Stack<>();
        int n = sc.nextInt();
        for (int i=0; i<n; i++) data.push(sc.nextInt());
        while (!data.isEmpty()) {
            int x = data.pop();
            if (st.isEmpty()) {
                st.push(x);
            } else {
                while (!st.isEmpty() && st.peek() > x)
                    data.push(st.pop());
                st.push(x);
            }
        }
        while (!st.isEmpty()) System.out.print(st.pop()+" ");
    }
}
public class Main{
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
        s.init();
    }
}
posted @ 2021-02-20 15:33  童年の波鞋  阅读(45)  评论(0编辑  收藏  举报