【数据结构】栈与队列区分push pop offer poll containsKey put等

目录

  • 前言
  • 正文
    • 队列
    • map集合

前言

算法中经常会用到栈和队列等数据结构
但是经常弄混他们的进与取的代码算法

此文主要是做一个区分度
用法以及注意事项详情可看我之前的文章
【数据结构】栈和队列详细分析(全)

正文

队列

如果使用队列的代码
其定义格式为:

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

其队列都是先进先出,进与取分为别offer以及poll

示意代码如下:
取每一层的最后一个节点,可以通过使用队列的方式进行存取

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                if (i == size - 1) {  //将当前层的最后一个节点放入结果列表
                    res.add(node.val);
                }
            }
        }
        return res;
    }
}

如果使用栈的代码
其定义格式为:

Deque<TreeNode> stk = new LinkedList<>();

其栈都是先进后出,进与取分为别push以及pop

示意代码如下:
中序遍历使用栈的方式进行存储

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<TreeNode>();

        while (root != null || !stk.isEmpty()) {
            while (root != null) {
               
                stk.push(root);
                 root = root.left;

            }

            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}

map集合

map集合中containsKey判断是否有这个key值,get获取key值,put放进key值
最典型的一道leetcode的题目如下:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map <Integer,Integer>map =new HashMap<>();
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(target-nums[i])) return new int[]{map.get(target-nums[i]),i};
            else map.put(nums[i],i);
        }
        return new int[0];
    }
}

你可能感兴趣的:(408专业,数据结构,java,链表)