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

The following examples show how to use java.util.Deque#offerFirst() . 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: NullAwayNativeModels.java    From NullAway with MIT License 6 votes vote down vote up
static void dequeStuff() {
  Deque<Object> d = new ArrayDeque<>();
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.add(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.addFirst(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.addLast(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.offerFirst(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.offerLast(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.offer(null);
  // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required
  d.push(null);
  Object[] o = null;
  // BUG: Diagnostic contains: passing @Nullable parameter 'o' where @NonNull is required
  d.toArray(o);
}
 
Example 2
Source File: CourseSchedule.java    From interview with Apache License 2.0 6 votes vote down vote up
private boolean topSort(int course, Neighbors[] graph, boolean[] used, Deque<Integer> stack, boolean[] dfs) {
    if (used[course]) {
        return false;
    }
    if (dfs[course]) {
        return true;
    }
    dfs[course] = true;
    for (int adj : graph[course].neighbor) {
        if (topSort(adj, graph, used, stack, dfs)) {
            return true;
        }
    }
    dfs[course] = false;
    used[course] = true;
    stack.offerFirst(course);
    return false;
}
 
Example 3
Source File: SimplyPath.java    From interview with Apache License 2.0 6 votes vote down vote up
public String simplifyPath(String path) {
    Deque<String> stack = new LinkedList<>();
    StringTokenizer token = new StringTokenizer(path, "/");
    while (token.hasMoreTokens()) {
        String tok = token.nextToken();
        if (tok.equals(".")) {
            continue;
        } else if (tok.equals("..")) {
            stack.pollFirst();
        } else {
            stack.offerFirst(tok);
        }
    }
    StringBuffer buff = new StringBuffer();
    if (stack.isEmpty()) {
        buff.append("/");
    }
    while(!stack.isEmpty()) {
        buff.append("/").append(stack.pollLast());
    }
    return buff.toString();
}
 
Example 4
Source File: SerializeDeserializeBinaryTree.java    From interview with Apache License 2.0 6 votes vote down vote up
/**
 * Deserialize Tree using level order traversal.
 */
public Node deserializeLevelOrder(String data) {
    if (data == null || data.length() == 0) {
        return null;
    }
    String[] input = data.split(",");
    Deque<Node> queue = new LinkedList<>();
    int index = 0;
    queue.offerFirst(Node.newNode(Integer.parseInt(input[index])));
    Node root = queue.peekFirst();
    index++;
    while (!queue.isEmpty()) {
        Node current = queue.pollFirst();
        if (index < input.length && !input[index].equals("%")) {
            current.left = Node.newNode(Integer.parseInt(input[index]));
            queue.offerLast(current.left);
        }
        index++;
        if (index < input.length && !input[index].equals("%")) {
            current.right = Node.newNode(Integer.parseInt(input[index]));
            queue.offerLast(current.right);
        }
        index++;
    }
    return root;
}
 
Example 5
Source File: LargerElementOnRight.java    From interview with Apache License 2.0 6 votes vote down vote up
public int[] larger(int input[]){
    Deque<Integer> stack = new LinkedList<Integer>();
    int result[] = new int[input.length];
    for(int i=0; i < result.length; i++){
        result[i] = -1;
    }
    
    stack.offerFirst(0);
    for(int i=1; i < input.length; i++){
        while(stack.size() > 0){
            int t = stack.peekFirst();
            if(input[t] < input[i]){
                result[t] = i;
                stack.pollFirst();
            }else{
                break;
            }
        }
        stack.offerFirst(i);
    }
    return result;
}
 
Example 6
Source File: RedissonDequeTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testOfferFirstOrigin() {
    Deque<Integer> queue = new ArrayDeque<Integer>();
    queue.offerFirst(1);
    queue.offerFirst(2);
    queue.offerFirst(3);

    assertThat(queue).containsExactly(3, 2, 1);
}
 
Example 7
Source File: SerializeDeserializeBinaryTree.java    From interview with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize tree using level order traversal.
 */
public String serializeLevelOrder(Node root) {
    if (root == null) {
        return "";
    }

    Deque<Node> queue = new LinkedList<>();
    queue.offerFirst(root);
    StringBuffer buff = new StringBuffer();
    while (!queue.isEmpty()) {
        root = queue.pollFirst();
        if (root == null) {
            buff.append("%,");
        } else {
            buff.append(root.data).append(",");
            queue.offer(root.left);
            queue.offer(root.right);
        }
    }
    for (int i = buff.length() - 1; i >= 0; i--) {
        if (buff.charAt(i) == '%' || buff.charAt(i) == ',') {
            buff.deleteCharAt(i);
        } else {
            break;
        }
    }
    return buff.toString();
}
 
Example 8
Source File: CousinNodes.java    From interview with Apache License 2.0 5 votes vote down vote up
public boolean areCousins(Node root, int a, int b) {
    Deque<Node> queue = new LinkedList<Node>();
    queue.offerFirst(root);
    int levelSize = 1;
    int tempLevelSize = 1;
    boolean foundFirst = false;
    while (!queue.isEmpty()) {
        levelSize = 0;
        while (tempLevelSize > 0) {
            Node node = queue.pollLast();
            // this is to make sure a and b are not siblings of each other
            // if they are return false since they cant be cousins
            if (checkSameParent(node, a, b)) {
                return false;
            }
            if (node.data == a || node.data == b) {
                if (foundFirst) {
                    return true;
                }
                foundFirst = true;
            }
            if (node.left != null) {
                queue.offerFirst(node.left);
                levelSize++;
            }
            if (node.right != null) {
                queue.offerFirst(node.right);
                levelSize++;
            }
            tempLevelSize--;
        }
        if (foundFirst) {
            return false;
        }
        tempLevelSize = levelSize;
    }
    return false;
}
 
Example 9
Source File: TreeTraversalInSpiralOrder.java    From interview with Apache License 2.0 5 votes vote down vote up
/**
 * One deque with delimiter to print tree in spiral order
 */
public void spiralWithOneDequeDelimiter(Node root)
{
    if(root == null){
        return;
    }
    Deque<Node> q = new LinkedList<>();
    q.offer(null);
    q.offerFirst(root);
    //if only delimiter(in this case null) is left in queue then break
    while(q.size() > 1){
        root = q.peekFirst();
        while(root != null){
            root = q.pollFirst();
            System.out.print(root.data + " ");
            if(root.left != null){
                q.offerLast(root.left);
            }
            if(root.right != null){
                q.offerLast(root.right);
            }
            root = q.peekFirst();
        }
        root = q.peekLast();
        while(root != null){
            System.out.print(root.data + " ");
            root = q.pollLast();
            if(root.right != null){
                q.offerFirst(root.right);
            }
            if(root.left != null){
                q.offerFirst(root.left);
            }
            root = q.peekLast();
        }
    }
}
 
Example 10
Source File: DefaultPooledObject.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized boolean endEvictionTest(
        final Deque<PooledObject<T>> idleQueue) {
    if (state == PooledObjectState.EVICTION) {
        state = PooledObjectState.IDLE;
        return true;
    } else if (state == PooledObjectState.EVICTION_RETURN_TO_HEAD) {
        state = PooledObjectState.IDLE;
        if (!idleQueue.offerFirst(this)) {
            // TODO - Should never happen
        }
    }

    return false;
}
 
Example 11
Source File: FluxExpand.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
boolean push(ExpandDepthSubscriber<T> subscriber) {
	synchronized (this) {
		Deque<ExpandDepthSubscriber<T>> q = subscriptionStack;
		if (q != null) {
			q.offerFirst(subscriber);
			return true;
		}
		return false;
	}
}
 
Example 12
Source File: ReverseStackUsingRecursion.java    From interview with Apache License 2.0 5 votes vote down vote up
private void pushAtBottom(Deque<Integer> stack,int data){
    if(stack.size() == 0){
        stack.offerFirst(data);
        return;
    }
    int temp = stack.pollFirst();
    pushAtBottom(stack, data);
    stack.offerFirst(temp);
}
 
Example 13
Source File: WallsAndGates.java    From interview with Apache License 2.0 5 votes vote down vote up
private  void addNeighbors(int[][] rooms, int row, int col, Deque<Cell> queue) {
    for (int[] d1 : d) {
        int r1 = row + d1[0];
        int c1 = col + d1[1];
        if (r1 < 0 || c1 < 0 || r1 >= rooms.length || c1 >= rooms[0].length || rooms[r1][c1] != INF) {
            continue;
        }
        rooms[r1][c1] = 1 + rooms[row][col];
        queue.offerFirst(new Cell(r1, c1));
    }
}
 
Example 14
Source File: WallsAndGates.java    From interview with Apache License 2.0 5 votes vote down vote up
private void gates(int[][] rooms, Deque<Cell> queue) {
    for (int i = 0; i < rooms.length; i++) {
        for (int j = 0; j < rooms[0].length; j++) {
            if (rooms[i][j] == 0) {
                queue.offerFirst(new Cell(i, j));
            }
        }
    }
}
 
Example 15
Source File: DirectedGraphConnectivity.java    From interview with Apache License 2.0 5 votes vote down vote up
private void DFSUtil(Vertex<Integer> vertex,
        Map<Vertex<Integer>, Boolean> visited, Deque<Vertex<Integer>> stack) {
    visited.put(vertex, true);
    for (Vertex<Integer> v : vertex.getAdjacentVertexes()) {
        if (visited.containsKey(v)) {
            continue;
        }
        DFSUtil(v, visited, stack);
    }
    stack.offerFirst(vertex);
}
 
Example 16
Source File: StronglyConnectedComponent.java    From interview with Apache License 2.0 5 votes vote down vote up
private void DFSUtil(Vertex<Integer> vertex,
        Set<Vertex<Integer>> visited, Deque<Vertex<Integer>> stack) {
    visited.add(vertex);
    for (Vertex<Integer> v : vertex.getAdjacentVertexes()) {
        if (visited.contains(v)) {
            continue;
        }
        DFSUtil(v, visited, stack);
    }
    stack.offerFirst(vertex);
}
 
Example 17
Source File: TopologicalSort.java    From interview with Apache License 2.0 5 votes vote down vote up
private void topSortUtil(Vertex<T> vertex, Deque<Vertex<T>> stack,
        Set<Vertex<T>> visited) {
    visited.add(vertex);
    for(Vertex<T> childVertex : vertex.getAdjacentVertexes()){
        if(visited.contains(childVertex)){
            continue;
        }
        topSortUtil(childVertex,stack,visited);
    }
    stack.offerFirst(vertex);
}
 
Example 18
Source File: DefaultPooledObject.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public synchronized boolean endEvictionTest(
        final Deque<PooledObject<T>> idleQueue) {
    if (state == PooledObjectState.EVICTION) {
        state = PooledObjectState.IDLE;
        return true;
    } else if (state == PooledObjectState.EVICTION_RETURN_TO_HEAD) {
        state = PooledObjectState.IDLE;
        if (!idleQueue.offerFirst(this)) {
            // TODO - Should never happen
        }
    }

    return false;
}
 
Example 19
Source File: TermMerger.java    From slr-toolkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Merges all terms into the target. 
 * @param termsToMerge All terms to merge, must contain the target.
 * @param targetTerm The target into which all terms will be merged.
 * @return The resulting, merged term. 
 */
public static Term merge(Collection<Term> termsToMerge, Term targetTerm) {
	// Merging can be dangerous, the case might occur in which the target term does not exist in a document
	// In this case, the target term must first be created for the document
	// find all documents that contain the target or, if not but the documents contains a term to merge than 
	// rebuild the target structure
	Map<Document, Term> documentsWithTarget = new HashMap<>();
	for (Document d : SearchUtils.getDocumentList()) {
		Term targetInDocument = SearchUtils.findTermInDocument(d, targetTerm);
		if (targetInDocument != null) {
			documentsWithTarget.put(d,  targetInDocument);
		} else {
			for (Term term : termsToMerge) {
				if (SearchUtils.findTermInDocument(d, term) != null) {
					// the target does not exist in d. However, d contains a term to merge
					// therefore, the target must be created
					// copied from TermMover TODO extract
					// build structure in document										
					Term targetDuplicate = EcoreUtil.copy(targetTerm);
					Deque<Term> taxonomyRebuild = new LinkedList<>();
					do {
						taxonomyRebuild.offerFirst(TaxonomyFactory.eINSTANCE.createTerm());
						taxonomyRebuild.peekFirst().setName(targetDuplicate.getName());
						targetDuplicate = targetDuplicate.eContainer() instanceof Term ? (Term) targetDuplicate.eContainer() : null;
					} while (targetDuplicate != null && SearchUtils.findTermInDocument(d, targetDuplicate) == null);
					Term rebuild = taxonomyRebuild.pollFirst();
					Term last = rebuild;
					while (taxonomyRebuild.peekFirst() != null) {						
						last.getSubclasses().add(taxonomyRebuild.peekFirst());
						last = taxonomyRebuild.pollFirst();						
					}
					if (targetDuplicate == null) {
						// dimension is missing
						d.getTaxonomy().getDimensions().add(rebuild);
					} else {
						// term is missing
						SearchUtils.findTermInDocument(d, targetDuplicate).getSubclasses().add(rebuild);
					}
					documentsWithTarget.put(d,  SearchUtils.findTermInDocument(d, term));
					break;
				}
			}
		}
	}
	
	// now merge all terms for the main taxonomy as well as for the taxonomies of the documents		
	// first, for each document, otherwise the terms would be manipulated
	Set<Resource> resourcesToUpdate = new TreeSet<>(
			(Resource r1, Resource r2) -> r1 == r2 ? 0 : 1);
	for (Map.Entry<Document, Term> entry : documentsWithTarget.entrySet()) {
		entry.getKey().setTaxonomy(doMerge(entry.getKey().getTaxonomy(), termsToMerge, entry.getValue()));
		resourcesToUpdate.add(entry.getKey().eResource());
	}		
	resourcesToUpdate.forEach(r -> BibtexFileWriter.updateBibtexFile(r));
	// secondly, for the main taxonomy
			Optional<Model> model = SearchUtils.getContainingModel(targetTerm);		
			if (model.isPresent()) {			
				TaxonomyUtils.saveTaxonomy(doMerge(model.get(), termsToMerge, targetTerm));
			}
	return SearchUtils.findTermInTaxonomy(targetTerm);
}
 
Example 20
Source File: TreeTraversalInSpiralOrder.java    From interview with Apache License 2.0 4 votes vote down vote up
/**
 * One deque with count method to print tree in spiral order
 */
public void spiralWithOneDeque(Node root) {
    if (root == null) {
        return;
    }
    Deque<Node> deque = new LinkedList<Node>();
    deque.offerFirst(root);
    int count = 1;
    boolean flip = true;
    while (!deque.isEmpty()) {
        int currentCount = 0;
        while (count > 0) {
            if (flip) {
                root = deque.pollFirst();
                System.out.print(root.data + " ");
                if (root.left != null) {
                    deque.offerLast(root.left);
                    currentCount++;
                }
                if (root.right != null) {
                    deque.offerLast(root.right);
                    currentCount++;
                }
            } else {
                root = deque.pollLast();
                System.out.print(root.data + " ");
                if (root.right != null) {
                    deque.offerFirst(root.right);
                    currentCount++;
                }
                if (root.left != null) {
                    deque.offerFirst(root.left);
                    currentCount++;
                }
            }
            count--;
        }
        flip = !flip;
        count = currentCount;
    }
}