4.栈相关

1.两个栈实现队列

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/

class CQueue {
    // 初始化两个栈完成队列功能;
    Stack<Integer> stack1 = null;
    Stack<Integer> stack2 = null;

    public CQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void appendTail(int a) {
        stack1.push(a);
    }

    public int deleteHead() {
        //  stack1中的元素倒序,添加到stack2中
        //  先添加元素,在请求出栈
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        //   元素出栈
        if (stack2.isEmpty()) {
            return -1;
        } else {
            return stack2.pop();
        }
    }
}

2.从尾到头打印链表

https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

	public int[] reversePrint(ListNode head) {
        // 遍历链表添加数据到栈中
        // 遍历栈赋值给数组
        Stack<Integer> s = new Stack<>();
        while(head != null){
            s.push(head.val);
            head = head.next;
        }
        int[] a = new int[s.size()];
        int i=0;
        while(!s.isEmpty()){
            a[i++] = s.pop();
        }
        return a;
    }

3.包含min函数的栈

https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/

class MinStack {
    // 两个栈实现,一个栈存放所有元素,
    Stack<Integer> stack1 = null;
    // 一个栈存放较小元素(每来一个元素和栈顶比较,若小则存放)
    Stack<Integer> stack2 = null;
    /** initialize your data structure here. */
    public MinStack() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    public void push(int x) {
        stack1.push(x);
        if(stack2.isEmpty() || stack2.peek() >= x){
            stack2.push(x);
        }
    }
    
    public void pop() {
        int a = stack1.pop();
        if(a == stack2.peek()){
            stack2.pop();
        }
    }
    
    public int top() {
          return  stack1.peek();
    }
    
    public int min() {
          return  stack2.peek();
    }
}

4..二叉搜索树与双向链表

https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/

class Solution {
    // 二叉搜索树的中序遍历,是递增的
    Node pre, head;

    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }
        // 转换为循环链表
        dfs(root);
        // 循环链表构建完成,head指针指向头结点,pre指针指向尾节点
        head.left = pre;
        pre.right = head;
        return head;
    }

    public void dfs(Node cur) {
        if (cur == null) {
            return;
        }
        // 中序遍历,左 根 右
        dfs(cur.left);
        if (pre == null) {
            head = cur;
        } else {
            pre.right = cur;
        }
        cur.left = pre;
        pre = cur;
        dfs(cur.right);
    }
}

2021.11.30 10:04

posted @ 2021-11-30 10:06  哟喝  阅读(34)  评论(0)    收藏  举报