Question

In: Computer Science

(In Java) Implement a Deque in which addFirst(), addLast(), removeFirst(), removeLast(), and getMin() are all in...

(In Java) Implement a Deque in which addFirst(), addLast(), removeFirst(), removeLast(), and getMin() are all in O(1) (amortized). The getMin() method is supposed to find the minimum value in the deque and update after ever add/remove. I tried implementing this with a Deque and LinkedList but wasn't successful, you do not need to use either. Must use the comparator and iterator. The goal is to be as fast as possible, so this includes avoiding any operations that aren't O(1) as much as possible. I used my own testing class. Thanks!

import java.util.*;

public class FMinDeque<T> implements MinDeque<T> {

    protected Comparator<? super T> comp;
    Deque<T> dq;
    protected List<T> min;
    T m;
    public FMinDeque() {
        this(new DefaultComparator<T>());
    }
    public FMinDeque(Comparator<? super T> comp) {
        this.comp = comp;
        dq = new ArrayDeque<T>();
        min = new LinkedList<T>();
    }
    public Comparator<? super T> comparator() {
        return comp;
    }
    public void addFirst(T x) {

    }
    public void addLast(T x) {

    }
    public T removeFirst() {
        
        return null;
    }
    public T removeLast() {
        
        return null;
    }
    public T getMin() {
      
    }
    public int size() {
        return dq.size();
    }
    public Iterator<T> iterator() {
        return dq.iterator();
    }
}

This extends:

import java.util.Comparator;

    public interface MinDeque<T> extends Iterable<T>
    {
        public Comparator<? super T> comparator();

        public void addFirst(T x);
        public void addLast(T x);

        public T removeFirst();
        public T removeLast();

        public T getMin();

        public int size();

And

import java.util.Comparator;

class DefaultComparator<T> implements Comparator<T> {
    @SuppressWarnings("unchecked")
    public int compare(T a, T b) {
        return ((Comparable<T>)a).compareTo(b);
    }
}

Solutions

Expert Solution

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Deque<Item> implements Iterable<Item> {
private Node first, last;
private int size;

// construct an empty deque
public Deque() {
first = null;
last = null;
size = 0;
}

// is the deque empty?
public boolean isEmpty() {
return first == null;
}

// return the number of items on the deque
public int size() {
return size;
}

// add the item to the front
public void addFirst(Item item) {
if (item == null) {
throw new IllegalArgumentException("Argument can't be null");
}

Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;

if (size == 0) {
last = first;
} else {
oldFirst.previous = first;
}

size++;
}

// add the item to the end
public void addLast(Item item) {
if (item == null) {
throw new IllegalArgumentException("Argument can't be null");
}

Node oldLast = last;
last = new Node();
last.item = item;
if (size == 0) {
first = last;
} else {
oldLast.next = last;
}
last.previous = oldLast;

size++;
}

// remove and return the item from the front
public Item removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException("No more items");
}
Item item = first.item;
first = first.next;

if (first != null) {
first.previous = null;
}

if (size == 1) {
last = null;
}

size--;
return item;
}

// remove and return the item from the end
public Item removeLast() {
if (isEmpty()) {
throw new NoSuchElementException("No more items");
}

Item item = last.item;
last = last.previous;

if (last != null) {
last.next = null;
}

if (size == 1) {
first = null;
}
size--;
return item;
}

// return an iterator over items in order from front to end
public Iterator<Item> iterator() {
return new DequeIterator();
}

// Using a LinkedList for this solution because of the performance requirement
// for constant worst case time
private class Node {
private Item item;
private Node next;
private Node previous;
}

private class DequeIterator implements Iterator<Item> {
private Node current = first;

public boolean hasNext() {
return current != null;
}

public void remove() {
throw new UnsupportedOperationException("Not implemented");
}

public Item next() {
if (!hasNext()) {
throw new NoSuchElementException("No more items");
}
Item item = current.item;
current = current.next;
return item;
}
}
}


Related Solutions

Program in java 1- Implement an algorithms to calculate the sum of all numbers in an...
Program in java 1- Implement an algorithms to calculate the sum of all numbers in an array.   2- Implement an algorithm to determine if an array has all unique integer values. 3- Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Write a java class for a Priority Queue. Use an arraylist, and include enque, deque, and...
Write a java class for a Priority Queue. Use an arraylist, and include enque, deque, and a method to get all the values of the queue. (This is not writing a file implementing the java class PriorityQueue, but rather you are writing a program that is a priority queue).
All code in JAVA please 1. Implement Insertion Sort 2. Implement Selection Sort *For problem 1...
All code in JAVA please 1. Implement Insertion Sort 2. Implement Selection Sort *For problem 1 and 2, please: a. Let the program generate a random array. b. Output both the original random array and the sorted version of it
Study and implement data structure deque (double ended queue, pronounced as "deck"). IN C++ PLEASE
Study and implement data structure deque (double ended queue, pronounced as "deck"). IN C++ PLEASE
In java the parts listed as todo in linkedsetwithlinkedbad Implement all the methods defined as skeletons...
In java the parts listed as todo in linkedsetwithlinkedbad Implement all the methods defined as skeletons in the LinkedSetWithLinkedBag class. The class implements the SetInterface (described in Segment 1.21 of chapter 1). It utilizes LinkedBag as defined in the UML diagram below: the instance variable setOfEntries is to be an object of LinkedBag. Test your class with the test cases provided in main. Do not make any changes to provided classes other than LinkedSetWithLinkedBag. Similar to Lab02, most of the...
A deque is a data structure consisting of a list of items, on which the following...
A deque is a data structure consisting of a list of items, on which the following operations are possible: • push(x): Insert item x on the front end of the deque. • pop(): Remove the front item from the deque and return it. • inject(x): Insert item x on the rear end of the deque. • eject(): Remove the rear item from the deque and return it. Write routines to support the deque that take O(1) time per operation. In...
Implement Library Sort in Java which is a version of Insertion Sort with gaps to speed...
Implement Library Sort in Java which is a version of Insertion Sort with gaps to speed up the computation. If the pseudocode in Wikipedia (https://en.wikipedia.org/wiki/Library_sort) is not enough, you can download the research paper from (https://arxiv. org/pdf/cs/0407003.pdf). Below is the algorithm and pseudo code. Implementation Algorithm Let us say we have an array of n elements. We choose the gap we intend to give. Then we would have a final array of size (1 + ε)n. The algorithm works in...
When should you choose a deque over a vector and a vector over a deque in...
When should you choose a deque over a vector and a vector over a deque in c++
Create a Deque class based on the following description of deque (double-ended queues). A dequeue is...
Create a Deque class based on the following description of deque (double-ended queues). A dequeue is a double-ended queue. You can insert items at either end and delete them from either end. Therefore, the deque offers two insert operations and two remove operations: insertLeft() and insertRight() removeLeft() and removeRight(). Deques may also have "peek" methods ( peekLeft() and peekRight() )that let you see the left or right item in the deque without remove the item from the deque. For this...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for managing a singly linked list that cannot contain duplicates. Default constructor Create an empty list i.e., head is null. boolean insert(int data) Insert the given data into the end of the list. If the insertion is successful, the function returns true; otherwise, returns false. boolean delete(int data) Delete the node that contains the given data from the list. If the deletion is successful, the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT