Question

In: Computer Science

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

Josie 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? (Java)

Solutions

Expert Solution

After reading the question, what I understand is that you need a Stack class with extra functionalities to check if an element exists on it and to remove a specified element. Here is the completed code for this problem including test code. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

//Stack.java class

public class Stack<T> {

      private Node top;

      // constructor initializing empty stack

      public Stack() {

            top = null;

      }

      // method to add an element to the top of the stack

      // run time complexity: O(1)

      public void push(T item) {

            // creating a new node, adding before top, and updating top

            Node n = new Node(item);

            n.next = top;

            top = n;

      }

      // method to remove an element from the top of the stack

      // run time complexity: O(1)

      public T pop() {

            if (top == null) {

                  // empty

                  return null;

            }

            // storing top element

            T item = top.data;

            // removing top

            top = top.next;

            // returning top

            return item;

      }

      // method to check if an element exists on the stack

      // run time complexity (worst time): O(n)

      public boolean contains(T item) {

            // looping and comparing each element with item

            for (Node n = top; n != null; n = n.next) {

                  if (n.data.equals(item)) {

                        // found

                        return true;

                  }

            }

            // not found

            return false;

      }

      // removes an element from the stack, returns true if found, else not

      public boolean remove(T item) {

            if (top == null) {

                  // empty

                  return false;

            }

            if (top.data.equals(item)) {

                  // removing top

                  top = top.next;

                  return true;

            }

            // taking top node

            Node temp = top;

            // looping and checking each node

            while (temp.next != null) {

                  if (temp.next.data.equals(item)) {

                        // removing temp.next

                        temp.next = temp.next.next;

                        return true;

                  }

                  temp = temp.next;

            }

            return false; // not found

      }

      // returns true if stack is empty

      public boolean isEmpty() {

            return top == null;

      }

      // an inner class representing a node in the linked chain

      class Node {

            T data;

            Node next;

            public Node(T data) {

                  this.data = data;

                  next = null;

            }

      }

     

      //code for testing

      public static void main(String[] args) {

            // creating a Stack

            Stack<Integer> stk = new Stack<Integer>();

            // pushing some elements

            stk.push(1);

            stk.push(2);

            stk.push(3);

            stk.push(4);

            // testing contains()

            System.out.println(stk.contains(3)); // true

            // testing remove()

            stk.remove(3);

            System.out.println(stk.contains(3)); // false

            // looping and popping stack until it is empty

            while (!stk.isEmpty()) {

                  // will print 4, then 2, then 1

                  System.out.println(stk.pop());

            }

      }

}

/*OUTPUT*/

true

false

4

2

1


Related Solutions

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?
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...
Using Python list tools, create the standard stack (push, pop) and queue (enqueue, dequeue) operations Counting...
Using Python list tools, create the standard stack (push, pop) and queue (enqueue, dequeue) operations Counting Letter Challenge: Create a function that... Takes in a string as parameter Counts how often each letter appears in the string Returns a dictionary with the counts BONUS: make it so lowercase and uppercase letter count for the same letter
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT