Java Code Examples for java.util.Deque#addLast()

The following examples show how to use java.util.Deque#addLast() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public void pathSum(TreeNode node, int sum, Deque<Integer> path, List<List<Integer>> res) {
    // 打开注释调试
    // System.out.println(path);

    // 递归终止条件
    if (node == null) {
        return;
    }

    // 沿途结点必须选择,这个时候要做两件事:1、sum 减去这个结点的值;2、添加到 path 里
    sum -= node.val;
    path.addLast(node.val);

    if (sum == 0 && node.left == null && node.right == null) {
        // path 全局只有一份,必须做拷贝
        res.add(new ArrayList<>(path));
        // 注意:这里 return 之前必须重置
        path.removeLast();
        return;
    }

    pathSum(node.left, sum, path, res);
    pathSum(node.right, sum, path, res);
    // 递归完成以后,必须重置变量
    path.removeLast();
}
 
Example 2
Source File: Solution3.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    if (root == null) {
        return res;
    }
    Deque<Command> stack = new ArrayDeque<>();
    stack.addLast(new Command(Action.GO, root));
    while (!stack.isEmpty()) {
        Command command = stack.removeLast();
        if (command.action == Action.ADDTORESULT) {
            res.add(command.node.val);
            continue;
        }

        if (command.node.right != null) {
            stack.add(new Command(Action.GO, command.node.right));
        }
        if (command.node.left != null) {
            stack.add(new Command(Action.GO, command.node.left));
        }
        stack.add(new Command(Action.ADDTORESULT, command.node));
    }
    return res;
}
 
Example 3
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
    // 先将 wordList 放到哈希表里,便于判断某个单词是否在 wordList 里
    List<List<String>> res = new ArrayList<>();
    Set<String> wordSet = new HashSet<>(wordList);
    if (wordSet.size() == 0 || !wordSet.contains(endWord)) {
        return res;
    }
    // 第 1 步:使用双向广度优先遍历得到后继结点列表 successors
    // key:字符串,value:广度优先遍历过程中 key 的后继结点列表
    Map<String, Set<String>> successors = new HashMap<>();
    boolean found = bidirectionalBfs(beginWord, endWord, wordSet, successors);
    if (!found) {
        return res;
    }
    // 第 2 步:基于后继结点列表 successors ,使用回溯算法得到所有最短路径列表
    Deque<String> path = new ArrayDeque<>();
    path.addLast(beginWord);
    dfs(beginWord, endWord, successors, path, res);
    return res;
}
 
Example 4
Source File: Solution3.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public void dfs(int[] candidates,
                Deque<Integer> path,
                int start,
                int currentSum,
                int target) {
    if (currentSum == target) {
        res.add(new ArrayList<>(path));
        return;
    }

    // 从起始位置开始尝试每一个可能的解
    for (int i = start; i < candidates.length; i++) {
        if (currentSum + candidates[i] <= target) {
            path.addLast(candidates[i]);
            currentSum += candidates[i];

            // 因为每一个数字可以重复使用多次,因此下一轮搜索还是从 i 开始
            dfs(candidates, path, i, currentSum, target);
            // 一轮搜索结束以后,状态需要重置,因此数字加上的要减去,列表末尾加上的要移除
            currentSum -= candidates[i];
            path.removeLast();
        }
    }
}
 
Example 5
Source File: Solution5.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public TreeNode mirrorTree(TreeNode root) {
    if (root == null) {
        return root;
    }

    Deque<TreeNode> stack = new ArrayDeque<>();
    stack.addLast(root);
    while (!stack.isEmpty()){
        TreeNode top = stack.removeLast();

        TreeNode temp =  top.left;
        top.left =  top.right;
        top.right = temp;

        if (top.left != null) {
            stack.offer(top.left);
        }
        if (top.right != null) {
            stack.offer(top.right);
        }
    }

    return root;
}
 
Example 6
Source File: LinkedListDemo02.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void main(String[] args) {
    Deque<String> list = new LinkedList<String>();
    list.add("A"); // 添加元素
    list.add("B"); // 添加元素
    list.add("C"); // 添加元素
    list.addFirst("X"); // 在头部添加元素
    list.addLast("Y"); // 在尾部添加元素
    System.out.println("初始化 LinkedList:" + list);
    System.out.println("1-1、element()方法找到表头:" + list.element());
    System.out.println("1-2、找完之后的链表的内容:" + list);
    System.out.println("2-1、peek()方法找到表头:" + list.peek());
    System.out.println("2-2、找完之后的链表的内容:" + list);
    System.out.println("3-1、poll()方法找到表头:" + list.poll());
    System.out.println("3-2、找完之后的链表的内容:" + list);

    System.out.print("以FIFO的方式输出:");
    for (int i = 0; i <= list.size() + 1; i++) {
        System.out.print(list.poll() + "、");
    }
}
 
Example 7
Source File: LeetCode93.java    From Project with Apache License 2.0 5 votes vote down vote up
public void splitIP(String s, int sLength, int residueSplitTimes, int beginIndex,
                    Deque<String> path, List<String> resList) {
    // 如果划分到结尾了,并且划分了 4 段,则返回
    if (beginIndex == sLength) {
        if (residueSplitTimes == 0) {
            resList.add(String.join(".", path));
        }
        return;
    }

    // 因为每一次划分都有三种可能性,一位,两位、三位
    for (int i = beginIndex; i < beginIndex + 3; i++) {
        if (i >= sLength) {
            break;
        }
        if (residueSplitTimes * 3 < sLength - i) {
            continue;
        }

        // 看上面三种划分是否结果能够构成 IP, 如果可以就是一种可能性,可以继续划分
        if (judgeIfIpSegment(s, beginIndex, i)) {
            String curIPSegment = s.substring(beginIndex, i + 1);
            path.addLast(curIPSegment);
            splitIP(s, sLength, residueSplitTimes - 1, i + 1, path, resList);
            path.removeLast();
        }
    }
}
 
Example 8
Source File: Solution5.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
private void dfs(int residue, int start, Deque<Integer> stack) {
    if (residue == 0) {
        res.add(new ArrayList<>(stack));
        return;
    }
    for (int i = start; i < len && residue - candidates[i] >= 0; i++) {
        stack.addLast(candidates[i]);
        dfs(residue - candidates[i], i, stack);
        stack.removeLast();
    }
}
 
Example 9
Source File: LeetCode93.java    From Project with Apache License 2.0 5 votes vote down vote up
public void splitIP(String s, int sLength, int residueSplitTimes, int beginIndex,
                    Deque<String> path, List<String> resList) {
    // 如果划分到结尾了,并且划分了 4 段,则返回
    if (beginIndex == sLength) {
        if (residueSplitTimes == 0) {
            resList.add(String.join(".", path));
        }
        return;
    }

    // 因为每一次划分都有三种可能性,一位,两位、三位
    for (int i = beginIndex; i < beginIndex + 3; i++) {
        if (i >= sLength) {
            break;
        }
        if (residueSplitTimes * 3 < sLength - i) {
            continue;
        }

        // 看上面三种划分是否结果能够构成 IP, 如果可以就是一种可能性,可以继续划分
        if (judgeIfIpSegment(s, beginIndex, i)) {
            String curIPSegment = s.substring(beginIndex, i + 1);
            path.addLast(curIPSegment);
            splitIP(s, sLength, residueSplitTimes - 1, i + 1, path, resList);
            path.removeLast();
        }
    }
}
 
Example 10
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
private void dfs(int[] nums, int begin, int len, Deque<Integer> path, List<List<Integer>> res) {
    res.add(new ArrayList<>(path));
    for (int i = begin; i < len; i++) {
        // 剪枝条件,不能写成 i > 0
        if (i > begin && nums[i] == nums[i - 1]){
            continue;
        }

        path.addLast(nums[i]);
        // 从 i + 1 开始继续枚举,按顺序枚举,所以不会重复
        dfs(nums, i + 1, len, path, res);
        path.removeLast();
    }
}
 
Example 11
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public boolean isSymmetric(TreeNode root) {
    if (root == null) {
        return true;
    }

    // 实现类不能选用 ArrayDeque,因为该类的 add 方法会对添加的元素做非空检查
    Deque<TreeNode> deque = new LinkedList<>();
    // Deque<TreeNode> deque = new ArrayDeque<>();

    deque.addFirst(root.left);
    deque.addLast(root.right);

    while (!deque.isEmpty()) {
        TreeNode leftNode = deque.removeFirst();
        TreeNode rightNode = deque.removeLast();

        if (leftNode == null && rightNode == null) {
            continue;
        }

        if (leftNode == null || rightNode == null) {
            return false;
        }

        if (leftNode.val != rightNode.val) {
            return false;
        }

        deque.addFirst(leftNode.right);
        deque.addFirst(leftNode.left);
        deque.addLast(rightNode.left);
        deque.addLast(rightNode.right);
    }

    return true;
}
 
Example 12
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public String removeDuplicateLetters(String s) {
    int len = s.length();
    // 特判
    if (len < 2) {
        return s;
    }

    char[] charArray = s.toCharArray();

    // 记录是否在已经得到的字符串中
    boolean[] set = new boolean[26];

    // 记录每个字符出现的最后一个位置
    int[] lastAppearIndex = new int[26];
    for (int i = 0; i < len; i++) {
        lastAppearIndex[charArray[i] - 'a'] = i;
    }

    Deque<Character> stack = new ArrayDeque<>();
    for (int i = 0; i < len; i++) {
        char currentChar = charArray[i];
        if (set[currentChar - 'a']) {
            continue;
        }

        while (!stack.isEmpty() && stack.peekLast() > currentChar && lastAppearIndex[stack.peekLast() - 'a'] >= i) {
            char top = stack.removeLast();
            set[top - 'a'] = false;
        }

        stack.addLast(currentChar);
        set[currentChar - 'a'] = true;
    }

    StringBuilder stringBuilder = new StringBuilder();
    while (!stack.isEmpty()) {
        stringBuilder.insert(0, stack.removeLast());
    }
    return stringBuilder.toString();
}
 
Example 13
Source File: ConditionBuilder.java    From Despector with MIT License 5 votes vote down vote up
private static void dfs(ConditionGraphNode next, Deque<Condition> stack) {

        // performs a depth-first-search to populate each node in the graph's
        // partial conditions

        if (!stack.isEmpty()) {
            // Add the condition up to this point to the partial conditions of
            // this node. This represents a path from the root to this node and
            // the condition of that path is the and of all simple conditions of
            // the nodes along the path
            if (stack.size() == 1) {
                next.addPartialCondition(stack.peek());
            } else {
                Condition partial = new AndCondition(stack);
                next.addPartialCondition(partial);
            }
        }
        if (next.getSimpleCondition() == null) {
            return;
        }
        // Push the simple condition of this node to the stack and recurse into
        // the target branch
        stack.addLast(next.getSimpleCondition());
        dfs(next.getTarget(), stack);
        stack.pollLast();
        // Same thing for the else_target except we push the inverse of this
        // node's condition
        stack.addLast(inverse(next.getSimpleCondition()));
        dfs(next.getElseTarget(), stack);
        stack.pollLast();
    }
 
Example 14
Source File: StellarCompiler.java    From metron with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked","ReferenceEquality"})
private void exitLambda(boolean hasArgs) {
  final FrameContext.Context context = getArgContext();
  Token<?> t = expression.tokenDeque.pop();
  final Deque<Token<?>> instanceDeque = new ArrayDeque<>();
  for(; !expression.tokenDeque.isEmpty() && t != EXPRESSION_REFERENCE; t = expression.tokenDeque.pop()) {
    instanceDeque.addLast(t);
  }
  final List<String> variables = hasArgs ? (List<String>) instanceDeque.removeLast().getValue() :new ArrayList<>();
  expression.tokenDeque.push(new Token<>((tokenDeque, state) -> {
    LambdaExpression expr = new LambdaExpression(variables, instanceDeque, state);
    tokenDeque.push(new Token<>(expr, Object.class, context));
  }, DeferredFunction.class, context));
}
 
Example 15
Source File: Solution6.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public List<String> generateParenthesis(int n) {
    List<String> res = new ArrayList<>();
    if (n == 0) {
        return res;
    }

    // 查看了 Stack 源码,官方推荐使用 Deque 对象,
    // 注意:只使用栈相关的接口,即 `addLast()` 和 `removeLast()`

    Deque<Node> stack = new ArrayDeque<>();
    stack.addLast(new Node("", n, n));

    while (!stack.isEmpty()) {

        Node curNode = stack.removeLast();
        if (curNode.left == 0 && curNode.right == 0) {
            res.add(curNode.res);
        }
        if (curNode.left > 0) {
            stack.addLast(new Node(curNode.res + "(", curNode.left - 1, curNode.right));
        }
        if (curNode.right > 0 && curNode.left < curNode.right) {
            stack.addLast(new Node(curNode.res + ")", curNode.left, curNode.right - 1));
        }
    }
    return res;
}
 
Example 16
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
/**
 * 从 [1, n] 中选出 k 个数,
 *
 * @param n     从 [1, n] 中选
 * @param k     选出的数字的个数
 * @param begin 当前被选中的起始数字
 * @param path  已经构成的数字列表
 */
private void dfs(int n, int k, int begin, Deque<Integer> path, List<List<Integer>> res) {
    if (path.size() == k) {
        res.add(new ArrayList<>(path));
        return;
    }

    for (int i = begin; i <= n; i++) {
        path.addLast(i);
        dfs(n, k, i + 1, path, res);
        path.removeLast();
    }
}
 
Example 17
Source File: BinaryTreeTraverser.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static <T> void pushIfPresent(Deque<T> stack, Optional<T> node) {
  if (node.isPresent()) {
    stack.addLast(node.get());
  }
}
 
Example 18
Source File: DirectoryWithSnapshotFeature.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Clean an inode while we move it from the deleted list of post to the
 * deleted list of prior.
 * @param bsps The block storage policy suite.
 * @param inode The inode to clean.
 * @param post The post snapshot.
 * @param prior The id of the prior snapshot.
 * @param collectedBlocks Used to collect blocks for later deletion.
 * @return Quota usage update.
 */
private static QuotaCounts cleanDeletedINode(
    final BlockStoragePolicySuite bsps, INode inode,
    final int post, final int prior,
    final BlocksMapUpdateInfo collectedBlocks,
    final List<INode> removedINodes) {
  QuotaCounts counts = new QuotaCounts.Builder().build();
  Deque<INode> queue = new ArrayDeque<INode>();
  queue.addLast(inode);
  while (!queue.isEmpty()) {
    INode topNode = queue.pollFirst();
    if (topNode instanceof INodeReference.WithName) {
      INodeReference.WithName wn = (INodeReference.WithName) topNode;
      if (wn.getLastSnapshotId() >= post) {
        wn.cleanSubtree(bsps, post, prior, collectedBlocks, removedINodes);
      }
      // For DstReference node, since the node is not in the created list of
      // prior, we should treat it as regular file/dir
    } else if (topNode.isFile() && topNode.asFile().isWithSnapshot()) {
      INodeFile file = topNode.asFile();
      counts.add(file.getDiffs().deleteSnapshotDiff(bsps, post, prior, file,
          collectedBlocks, removedINodes));
    } else if (topNode.isDirectory()) {
      INodeDirectory dir = topNode.asDirectory();
      ChildrenDiff priorChildrenDiff = null;
      DirectoryWithSnapshotFeature sf = dir.getDirectoryWithSnapshotFeature();
      if (sf != null) {
        // delete files/dirs created after prior. Note that these
        // files/dirs, along with inode, were deleted right after post.
        DirectoryDiff priorDiff = sf.getDiffs().getDiffById(prior);
        if (priorDiff != null && priorDiff.getSnapshotId() == prior) {
          priorChildrenDiff = priorDiff.getChildrenDiff();
          counts.add(priorChildrenDiff.destroyCreatedList(bsps, dir,
              collectedBlocks, removedINodes));
        }
      }
      
      for (INode child : dir.getChildrenList(prior)) {
        if (priorChildrenDiff != null
            && priorChildrenDiff.search(ListType.DELETED,
                child.getLocalNameBytes()) != null) {
          continue;
        }
        queue.addLast(child);
      }
    }
  }
  return counts;
}
 
Example 19
Source File: BinaryTreeTraverser.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static <T> void pushIfPresent(Deque<T> stack, Optional<T> node) {
  if (node.isPresent()) {
    stack.addLast(node.get());
  }
}
 
Example 20
Source File: Solution513.java    From LeetCodeSolution with Apache License 2.0 3 votes vote down vote up
/**
 * 1.关于复杂度
 *     1.1 时间复杂度为O(n)
 *     1.2 空间负责度为O(n)
 * 2.我的解题思路
 *     2.1 这个解法基于BFS
 *     2.2 传统的BFS,但是在元素入队时右孩子先入队,左孩子后入队
 * 3.提交记录
 *     3.1 力扣中耗时4ms,消耗38.9MB内存
 *     3.2 leetcode中耗时1ms,消耗39.5MB内存
 * 4.Q&A
 *
 * 1.About Complexity
 *     1.1 Time Complexity is O(n)
 *     1.2 Space Complexity is O(n)
 * 2.how I solve
 *     2.1 this solution is base on BFS
 *     2.2 define a queue and from right to left enqueue treeNode
 * 3.About submit record
 *     3.1 4ms and 38.9MB memory in LeetCode China
 *     3.2 1ms and 39.5MB memory in LeetCode
 * 4.Q&A
 *
 * @param root
 * @return
 */
public int findBottomLeftValueByBFS(BinaryTreeNode root) {
    Deque<BinaryTreeNode> queue=new LinkedList<>();
    queue.addLast(root);
    while(queue.size()!=0){
        root=queue.pollFirst();
        if(root.right!=null){
            queue.addLast(root.right);
        }
        if(root.left!=null){
            queue.addLast(root.left);
        }
    }
    return root.val;
}