• 倒序思维~ (增删都在头部)一种 栈 思维


    倒序思维~ (增删都在头部)一种 栈 思维

    ✿具体代码:

    双端队列Deque可以作为栈的底层用子类双端链表 LinkedList 作为具体实现类,来实现栈的功能

    ②动态数组,  (想到动态数组,将数据插入到 下标为 0 的位置)

    ☺ 例子1: 动态数组:

        //从叶子到根的遍历(层序遍历)~ 思路:倒序:只需要不断插入第一个位置
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<Integer> item = new ArrayList<>();
            List<List<Integer>> result = new ArrayList<>();
            if(root == null)     return result;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            int levelSize = 1;
            while(!queue.isEmpty()) {
                TreeNode node = queue.poll();
                levelSize--;
                item.add(node.val);
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
                if(levelSize == 0) {
                    result.add(0, item);
                    item = new ArrayList<>();
                    levelSize = queue.size();
                }
            }        
            return result;
        }

    ☺例子2:双端链表LinkedList:

        //19_删除链表的倒数第N个结点
        // 通过栈(后进先出(pop掉 后面 第N个,从而可以拿到待删除结点的前一个结点))~  倒序思维~ 联想到数据结构栈
        class Solution2 {
            public ListNode removeNthFromEnd(ListNode head, int n) {
                ListNode dummy = new ListNode(0, head);
                Deque<ListNode> stack = new LinkedList<ListNode>();
                ListNode cur = dummy;
                while (cur != null) {
                    stack.push(cur);
                    cur = cur.next;
                }
                for (int i = 0; i < n; ++i) {
                    stack.pop();
                }
                ListNode prev = stack.peek();
                prev.next = prev.next.next;
                ListNode ans = dummy.next;
                return ans;
            }
        }
  • 相关阅读:
    offer
    ubuntu中常用软件的安装
    个人学习连接
    七月在线算法班作业
    程序设计1
    Adaptive Decontamination of the Training Set: A Unified Formulation for Discriminative Visual Tracking
    correlation filters in object tracking2
    correlation filters in object tracking
    学习网站
    从熵到交叉熵损失函数的理解
  • 原文地址:https://www.cnblogs.com/shan333/p/15449705.html
Copyright © 2020-2023  润新知