数据结构 -- 02 -- 栈与队列

203 阅读1分钟

栈结构的特点: 后进先出

Stack<Integer> stack = new Stack();

应用场景举例:

1.进制转换问题:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Stack<Integer> stack = new Stack<>();
    int n = 0;
    System.out.print("请输入10进制数: ");
    n = sc.nextInt();
    while(n > 0){
        stack.push(n % 2);
        n /= 2;
    }

    System.out.print("二进制: ");
    while(!stack.empty()){
        System.out.print(stack.peek());
        stack.pop();
    }
}

2.括号(多种)匹配问题:

public static void main(String[] args) {
    Scanner sc = new Scanner((System.in));
    String line;
    Stack<Character> stack = new Stack();
    HashMap<Character, Integer> map = new HashMap<>();
    
    map.put('(', 1);
    map.put('[', 2);
    map.put('{', 3);
    map.put(')', 4);
    map.put(']', 5);
    map.put('}', 6);
    
    
    
    System.out.print("输入表达式: ");
    line = sc.nextLine();

    //标记是否匹配
    boolean flag = true;
    for (int i = 0; i < line.length(); i++) {
        char c = line.charAt(i);
        //存在于Map中
        if(map.containsKey(c)){
            int k = map.get(c);
            //说明为左括号
            if(k <= 3){
                stack.push(c);
            } else if(!stack.empty()){
                //说明不匹配
                if(map.get(stack.peek()) != k - 3){
                    flag = false;
                }
                stack.pop();
            } else{
                //右括号过多
                flag = false;
            }
        }
    }
    
    //判断结果
    if(flag){
        System.out.println("匹配成功");
    } else{
        System.out.println("匹配失败");
    }
}

3.火车进栈问题:

static int n;
static int state1 = 1;
static Stack<Integer> state2 = new Stack<>();
static ArrayList<Integer> state3 =new ArrayList<>();


static void dfs(){
    //全部出栈
    if(state3.size() == n) {
        for (Integer x : state3) {
            System.out.print(x + " ");
        }
        System.out.println();
        return;
    }
    //如果栈非空,
    if(!state2.empty()){
        state3.add(state2.pop());
        dfs();
        state2.push(state3.get(state3.size() - 1));
        state3.remove(state3.size() - 1);
        
    }
    //如果存在待入栈元素
    if(state1 <= n){
        state2.push(state1);
        state1 ++;
        dfs();
        state1 --;
        state2.pop();
    }
}

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("输入火车数量: ");
    n = sc.nextInt();
    dfs();
}

4.表达式求值问题:

5.逆波兰式:

后续代码日后补上

队列

队列结构的特点:先进先出,尾进头出

队列很少有单独的使用场景,通常是配合一些算法进行使用

Java中LinkedList是基于Queue实现的

Queue<Integer> queue = new LinkedList<();