Question

In: Computer Science

Ellie needs a data structure that can handle the following operations: push, pop, contains, remove, where...

Ellie needs a data structure that can handle the following operations: push, pop, contains, remove, where contains(Item x) answers whether a given item is in the data structure and remove(Item x) removes the given item from the data structure. How can this be implemented efficiently?

Solutions

Expert Solution

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;

public class MyStack {
        
        static class Node {
                int value;
                Node next;
                Node prev;
                
                public Node(int x, Node next) {
                        this.value = x;
                        this.next = next;
                }
        }
        
        Node stack = null;
        
        // to keep count of each element
        // HashSet can not be used alone, Since, We need to push and pop
        private HashMap<Integer, ArrayList<Node>> hashSet = new HashMap<>();
        
        public void push(int x) {
                stack = new Node(x, stack);
                if(stack.next != null) {
                        stack.next.prev = null;
                }
                
                ArrayList<Node> nodeAddresses = hashSet.getOrDefault(x, new ArrayList<>());
                nodeAddresses.add(0, stack);
                hashSet.put(x, nodeAddresses);
        }
        
        public int pop() {
                if(stack == null) {
                        throw new IllegalArgumentException("pop on empty list");
                }
                Node x = stack;
                stack = stack.next;
                if(stack != null) {
                        stack.prev = null;
                }
                hashSet.get(x.value).remove(0);
                return x.value;
        }
        
        public boolean contains(int x) {
                return hashSet.containsKey(x) && !hashSet.get(x).isEmpty();
        }
        
        public boolean remove(int x) {
                ArrayList<Node> nodeAddresses = hashSet.get(x);
                if(nodeAddresses == null) {
                        return false;
                }
                
                Node node = nodeAddresses.remove(0);
                
                if(node.prev != null) {
                        node.prev.next = node.next;
                } else {
                        stack = node.next;
                        stack.prev = null;
                }
                
                return true;
        }
        
        public static void main(String[] args) {
                MyStack s = new MyStack();
                s.push(10);
                s.push(20);
                s.push(30);
                s.push(10);
                s.push(20);
                
                s.remove(20); // remove one occurrence.
                System.out.println(s.pop());
                System.out.println(s.pop());
                System.out.println(s.pop());
                System.out.println(s.pop());
                
        }

}
**************************************************
Created the stack with the node addresses stored in an hashmap, Hence we can easily remove the nodes in between the stack, which in general is not allowed from the stack. Remove is an O(1) operation thus, and so are push, pop and contains.

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

Problem A. The pseudocode as below illustrates the basic push() and pop() operations of an array-based...
Problem A. The pseudocode as below illustrates the basic push() and pop() operations of an array-based stack, where top is initialized as 0 when the stack is empty. Assuming that at a given moment, SIZE is equal to 20, top is equal to 8, this code is used in a concurrent environment (top and stack[] are in shared memory section), process P0 is about to call push() and process P1 is about to call pop() concurrently a. Which variable has...
Reverse the contents of a stack using only stack operations [ push() and pop()  ]. Using the...
Reverse the contents of a stack using only stack operations [ push() and pop()  ]. Using the java and give the explanation
5 marks] A MinStack supports three main operations: the standard Stack operations push(x) and pop() and...
5 marks] A MinStack supports three main operations: the standard Stack operations push(x) and pop() and the non-standard min() operation which returns the minimum value stored on the stack. The zip file gives an implementation SlowMinStack that implements these operations so that push(x) and pop() each run in O(1) time, but  min()runs in Θ(n) time. For this question, you should complete the implementation of FastMinStack that implements all three operations in O(1) time per operation. As part of your implementation, you...
Binomial Hypothesis Test. While this method is limited in the type of data it can handle...
Binomial Hypothesis Test. While this method is limited in the type of data it can handle (binary - "success/failure" outcomes), it is powerful in providing figures of authority with scientific information off of which to base important decisions. There is a limitation to using this method and, statistically, this notion refers to the "power" of a test. First, let's suppose that you are a disease outbreak coordinator for the Center for Disease Control and Prevention. A recent flu outbreak has...
When can the Coase Theorem properly handle a situation where an externality exists? Provide an example....
When can the Coase Theorem properly handle a situation where an externality exists? Provide an example. In what types of situations can the Coase Theorem not properly handle an externality? How can they be addressed instead?
The Big Push model illustrates alternative cases where the economy can reach equilibrium with a higher...
The Big Push model illustrates alternative cases where the economy can reach equilibrium with a higher level of total output with coordinated efforts by modern firms and cases where such an outcome is impossible despite such efforts. Explain with a graph only the case where there exists a possibility of a coordination failure. Suppose that a developing country devotes extensive resources towards improving the education and skill level of the labor force. How might this help the economy avoid a...
Write a program that uses linked lists in order to support the following operations: 1. PUSH...
Write a program that uses linked lists in order to support the following operations: 1. PUSH (S, x) - pushes a value x into a stack S 2. POP (S, i) - gets a number i (positive integer) and pops i numbers of S. If S contains less than i values, the operation is impossible to execute (program prints ERROR in this case – see below). 3. REVERSE (S) - reverse the order of the elements in S (you might...
/** * Interface for a set data type that supports adding, removing and contains operations. *...
/** * Interface for a set data type that supports adding, removing and contains operations. * @param <T> the type parameter for the elements of the set */ interface SetADT<T> { /** * Add a new element to the set. * @param el the new element to add to the set * @return true if the element has been added to the set, false if it was already in the set * @throws IllegalArgumentException if the new element passed to...
If the file circuit.txt contains the following data
Exercise 2: If the file circuit.txt contains the following data 3.0             2.1 1.5             1.1 2.6             4.1 The first column is voltage and the second column is the electric current. Write program that reads the voltages and currents then calculates the electric power (P) based on the equation: Voltage     Current        Power 3.0             2.1              (result) 1.5             1.1              (result) 2.6             4.1              (result)                         P = v * i Write your output to the file results.txt with voltage in the first, current in the second...
The following table contains data from 16 former elementary statistics students, where x represents the number...
The following table contains data from 16 former elementary statistics students, where x represents the number of absences a student had for the semester and y represents the student’s final class average. Absences Class Average 2 86 2 83 3 81 10 53 3 92 7 71 9 68 1 79 12 53 9 78 1 77 1 85 13 62 1 97 10 54 3 79 (a) Draw a scatter plot using one the following website(s): http://www.alcula.com/calculators/statistics/scatter-plot/ or https://www.meta-chart.com/scatter...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT