Double Ended Queue - java

The goal is to develop a java program to implement a Dqueue in an efficient manner for all the 6 methods below. I have to Extend java.util.LinkedList to Dqueue and implement all of the methods below.
public void enqueHead(E element),
public void enqueTail(E element)
public E dequeHead()
public E dequeTail()
public E peekHead() that returns the element at the Head but not remove it.
public E peekTail() that returns the element at the Tail but not remove it.
I have come up with the following code:
import java.util.LinkedList;
public class Dqueue<E> extends LinkedList<E> {
public void enqueHead(E element) {
if (isEmpty()) {
add(element);
return;
}
add(0, element);
}
public void enqueTail(E element) {
add(element);
}
public E dequeHead() {
if (isEmpty()) {
return null;
}
return remove(0);
}
public E dequeTail() {
if (isEmpty()) {
return null;
}
return remove(size() - 1);
}
public E peekHead() {
if (isEmpty()) {
return null;
}
return get(0);
}
public E peekTail() {
if (isEmpty()) {
return null;
}
return get(size() - 1);
}
}
I know that A double ended queue is much like a queue except that the operations of enqueing (adding) and dequeing (removing) can be done at both ends of the queue. In a conventional queue, the enque operation is done at the tail and deque is done at the tail but in a Dqueue these operations are allowed at both ends. My only question is if I am doing this correctly? Because it feels a little too simple for it to be right.

Related

In java implementation of Singly Linked List, Why is the last element of the linked list not being printed?

public class Linked_List <E>{
public static class Node<E>{
private E element;
private Node<E> next;
public Node(E e,Node<E> n) {
element=e;
next=n;
}
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> n) {
next=n;
}
}
public Node<E> head=null;
public Node<E> tail=null;
public int size=0;
public Linked_List() {}
public int size() {
return size;
}
public boolean isEmpty() {
return size==0;
}
public void addFirst(E e) {
head=new Node<>(e,head);
if(size==0)
head=tail;
size++;
}
public void addLast(E e) {
Node<E> newest =new Node<>(e,null);
if(isEmpty())
head=newest;
else
tail.setNext(newest);
tail=newest;
size++;
}
public void show() {
Node<E> n=head;
if(size==0) {
System.out.println("No elements to print");
System.exit(0);
}
while(n.next!=null) {
System.out.println(n.element);
n=n.next;
}
System.out.println(n.element);
}
public static void main(String[] args) {
Linked_List<Integer> list = new Linked_List<Integer>();
list.addFirst(10);
list.addFirst(11);
list.addFirst(12);
list.show();
}
}
In show() method when the while reaches the last element of the list, it exits so the element doesn't get printed. Hence the last print statement in the show method.
I have added three elements into the list but when I execute the show() method only the first two elements that is 12 and 11 get printed. What is it that i am missing? Thanks.
How about here. This should say tail = head;
public void addFirst(E e) {
head = new Node<>(e, head);
if (size == 0) {
head = tail;
}
size++;
}
addFisrt() change to:
public void addFirst(E e) {
head = new Node<>(e, head);
size++;
}
you can debug addFirst(), the first element never add to LinkedList.
The problem is in the while loop condition:
while(n.next!=null) {
System.out.println(n.element);
n=n.next;
}
When the list reaches element n-1 it will print the element and then n will become n=n.next which is the last element. But now n being the last element his n.next will be null therefore while will break since the condition is not met anymore.
You answered your own question:
In show() method when the while reaches the last element of the list,
it exits so the element doesn't get printed.
This code:
while(n.next!=null) {
System.out.println(n.element);
n=n.next;
}
says "while it's not the last element, print it". i.e., the code explicitly does not want to print the last element.
I am here assuming that you're not including the final print statement in your problem description - that you added the final print to work around the while-loop problem.
You need:
while (n != null) {
System.out.println(n.element);
n = n.next;
}
which says 'while it is an actual element, print it'.

java iterator could not be applied to for_each

I try to build an Linked Positional List myself when learning Data Structures and Algorithms in Java 6th Edition.
Position implements Node to store data.
I want to build two iterators,one for iterating Position and another for iterate the element in the Position. So I think two kinds of for-each loop could be applied as the following:
LinkedPositionalList<String> list = new LinkedPositionalList<>();
list.addFirst("A");
list.addLast("B");
list.addLast("V");
for (Position posi : list.positions()) {
}
for (String str:list ) {
}
It turns out that the second for-each not applicable to type,but the first one works well. So how to make the second for-each iterator work?
This is my code for building such class:
p.s.:The code is very long.The last part of nested class tried to implement the Iterator interface.The code before that is the way to build Linked Positional List which I think is not important...
public class LinkedPositionalList<E> implements PositionalList<E> {
private static class Node<E> implements Position<E> {
private E element;
private Node<E> prev;
private Node<E> next;
public Node(E e, Node<E> p, Node<E> n) {
element=e;
prev=p;
next=n;
}
public E getElement() throws IllegalStateException {
if (next == null) {
throw new IllegalStateException("Position no longer valid");
}
return element;
}
public Node<E> getPrev() {
return prev;
}
public Node<E> getNext() {
return next;
}
public void setElement(E e) {
element=e;
}
public void setPrev(Node<E> prev) {
this.prev = prev;
}
public void setNext(Node<E> next) {
this.next=next;
}
}
private Node<E> header;
private Node<E> trailer;
private int size=0;
public LinkedPositionalList() {
header = new Node<>(null, null, null);
trailer = new Node<>(null, header, null);
header.setNext(trailer);
}
private Node<E> validate(Position p)throws IllegalArgumentException {
if (!(p instanceof Node)) {
throw new IllegalArgumentException("Invalid p");
}
Node<E> node=(Node<E>)p;
if (node.getNext() == null) {
throw new IllegalArgumentException("p is no longer in the list");
}
return node;
}
private Position<E> position(Node<E> node) {
if (node == header || node == trailer) {
return null;
}
return node;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public Position<E> first() {
return position(header.getNext());
}
public Position<E> last() {
return position(trailer.getPrev());
}
public Position<E> before(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return position(node.getPrev());
}
public Position<E> after(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return position(node.getNext());
}
public Position<E> addBetween(E e, Node<E> pred, Node<E> succ) {
Node<E> newest = new Node<>(e, pred, succ);
pred.setNext(newest);
succ.setPrev(newest);
size++;return newest;
}
public Position<E> addFirst(E e) {
return addBetween(e, header, header.getNext());
}
public Position<E> addLast(E e) {
return addBetween(e, trailer.getPrev(), trailer);
}
public Position<E> addBefore(Position<E> p, E e) throws IllegalArgumentException {
Node<E> node = validate(p);
return addBetween(e, node.getPrev(), node);
}
public Position<E> addAfter(Position<E> p,E e) throws IllegalArgumentException {
Node<E> node = validate(p);
return addBetween(e,node,node.getNext());
}
public E set(Position<E> p, E e) throws IllegalArgumentException {
Node<E> node = validate(p);
E answer = node.getElement();
node.setElement(e);
return answer;
}
public E remove(Position<E> p)throws IllegalArgumentException {
Node<E> node = validate(p);
Node<E> pre = node.getPrev();
Node<E> succ = node.getNext();
pre.setNext(succ);
succ.setPrev(pre);
size--;
E answer = node.getElement();
node.setNext(null);
node.setPrev(null);
node.setElement(null);
return answer;
}
//Here is the part that I think should be redesigned!!!!
private class PositionIterator implements Iterator<Position<E>> {
private Position<E> cursor = first(); // position of the next element to report
private Position<E> recent = null; // position of last reported element
public boolean hasNext() { return (cursor != null); }
public Position<E> next() throws NoSuchElementException {
if (cursor == null) throw new NoSuchElementException("nothing left");
recent = cursor; // element at this position might later be removed
cursor = after(cursor);
return recent;
}
public void remove() throws IllegalStateException {
if (recent == null) throw new IllegalStateException("nothing to remove");
LinkedPositionalList.this.remove(recent); // remove from outer list
recent = null; // do not allow remove again until next is called
}
} //------------ end of nested PositionIterator class ------------
//---------------- nested PositionIterable class ----------------
private class PositionIterable implements Iterable<Position<E>> {
public Iterator<Position<E>> iterator() { return new PositionIterator(); }
} //------------ end of nested PositionIterable class ------------
public Iterable<Position<E>> positions() {
return new PositionIterable(); // create a new instance of the inner class
}
//---------------- nested ElementIterator class ----------------
private class ElementIterator implements Iterator<E> {
Iterator<Position<E>> posIterator = new PositionIterator();
public boolean hasNext() { return posIterator.hasNext(); }
public E next() { return posIterator.next().getElement(); } // return element!
public void remove() { posIterator.remove(); }
}
public Iterator<E> iterator() { return new ElementIterator(); }
}
For the built-in Java Collection Framework classes, if you just want the items, use:
for (String item : list) {
// do something with item
}
To use an explicit iterator (so you could, for instance, use the iterator's remove() method), you use a regular for loop:
for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) {
String item = iter.next();
// do something with item
}
Of course, you can also use a while loop.
For your particular class, it's hard to tell if the above applies because you haven't posted the definition of PositionalList.
Replace the inner loop with:
for (String str : list) {
}
That is the correct syntax for the Java for-each loop.

how to realize a queue in java?

I want to do the same thing I did in this code for stack
how can i change it so it will be for queue? I don't want to use stack or LinkedList for that
public StackAsArray(){
this(new DynamicArray());
}
public boolean isEmpty() {
}
public void push(Object o) {
}
public Object pop() {
}
}
You just need to replace your push and pop methods with enqueue and dequeue methods.
enqueue adds elements to the end of the array, while dequeue will remove it from the beginning.
public class QueueAsArray implements Queue {
...
public void enqueue(Object o) {
arr.set(numOfElements, o);
numOfElements++;
}
public Object dequeue() {
if(isEmpty()) { // an empty check is a MUST
return null;
}
numOfElements = numOfElements - 1;
Object res = arr.get(0);
arr.set(0, null); // not 100% sure this works, but since this is a homework question, its upto you to figure out. The logic is to remove the 0th element.
return res;
}
}

Incompatible Types Error in Java

I keep receiving an error that says that there are incompatible types. I copied this directly out of a book because we are supposed to make changes to the code to enhance the game of War. I have all of the other classes complete and compiled but this one is giving me fits. Here is the code:
public class ArrayStack<E> implements Stack<E> {
private E[] data;
private int size;
public ArrayStack() {
data = (E[])(new Object[1]);
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public Object pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public Object peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
protected boolean isFull() {
return size == data.length;
}
public void push(Object target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
protected void stretch() {
E[] newData = (E[])(new Object[data.length * 2]);
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
}
The error is occurring in the push() method at the data[size] = target; line.
EDIT:::
I'm now receiving this error.
"type Stack does not take parameters
public class ArrayStack implements Stack"
The stack class is as follows.
public interface Stack<E> {
public boolean isEmpty();
public E peek();
public E pop();
public void push(E target);
}
Change Object to E as the push() method's parameter type.
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
Likewise, you should also change the declare return type of pop() and peek() to E.
public E pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public E peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
Now your class is fully generic.
push method is not generic like the rest of the class, change it to:
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
In any case the JDK ships with the class ArrayDeque which fulfill your requirements without being a piece o code pasted from a book.
ArrayDeque<YourObj> stack = new ArrayDeque<YourObj>();
stack.push(new YourObj());
YourObj head = stack.peek();
head = stack.pop();

Best implementation of Java Queue?

I am working (in Java) on a recursive image processing algorithm that recursively traverses the pixels of the image, outwards from a center point.
Unfortunately, that causes a Stack Overflow. So I have decided to switch to a Queue-based algorithm.
Now, this is all fine and dandy- but considering the fact that its queue will be analyzing THOUSANDS of pixels in a very short amount of time, while constantly popping and pushing, WITHOUT maintaining a predictable state (It could be anywhere between length 100, and 20000), the queue implementation needs to have significantly fast popping and pushing abilities.
A linked list seems attractive due to its ability to push elements onto itself without rearranging anything else in the list, but in order for it to be fast enough, it would need easy access to both its head, AND its tail (or second-to-last node if it were not doubly-linked). Sadly, I cannot find any information related to the underlying implementation of linked lists in Java, so it's hard to say if a linked list is really the way to go...
This brings me to my question. What would be the best implementation of the Queue interface in Java for what I intend to do? (I do not wish to edit or even access anything other than the head and tail of the queue -- I do not wish to do any sort of rearranging, or anything. On the flip side, I DO intend to do a lot of pushing and popping, and the queue will be changing size quite a bit, so preallocating would be inefficient)
Use:
Queue<Object> queue = new LinkedList<>();
You can use .offer(E e) to append an element to the end of the queue and .poll() to dequeue and retrieve the head (first element) of the queue.
Java defined the interface Queue, the LinkedList provided an implementation.
It also maintains references to the Head and Tail elements, which you can get by .getFirst() and .getLast() respectively.
credit to #Snicolas for suggesting queue interface
If you use LinkedList be careful. If you use it like this:
LinkedList<String> queue = new LinkedList<String>();
then you can violate queue definition, because it is possible to remove other elements than first (there are such methods in LinkedList).
But if you use it like this:
Queue<String> queue = new LinkedList<String>();
it should be ok,as this is heads-up to users that insertions should occur only at the back and deletions only at the front.
You can overcome defective implementation of the Queue interface by extending the LinkedList class to a PureQueue class that throws UnsupportedOperationException of any of the offending methods. Or you can take approach with aggreagation by creating PureQueue with only one field which is type LinkedList object, list, and the only methods will be a default constructor, a copy constructor, isEmpty(), size(), add(E element), remove(), and element(). All those methods should be one-liners, as for example:
/**
* Retrieves and removes the head of this queue.
* The worstTime(n) is constant and averageTime(n) is constant.
*
* #return the head of this queue.
* #throws NoSuchElementException if this queue is empty.
*/
public E remove()
{
return list.removeFirst();
} // method remove()
Check out the Deque interface, which provides for insertions/removals at both ends. LinkedList implements that interface (as mentioned above), but for your use, an ArrayDeque may be better -- you won't incur the cost of constant object allocations for each node. Then again, it may not matter which implementation you use.
Normal polymoprhism goodness comes to play: the beauty of writing against the Deque interface, rather than any specific implementation of it, is that you can very easily switch implementations to test which one performs best. Just change the line with new in it, and the rest of the code stays the same.
It's better to use ArrayDeque instead of LinkedList when implementing Stack and Queue in Java. ArrayDeque is likely to be faster than Stack interface (while Stack is thread-safe) when used as a stack, and faster than LinkedList when used as a queue. Have a look at this link Use ArrayDeque instead of LinkedList or Stack.
If you know the upper bound of possible quantity of items in the queue, circular buffer is faster than LinkedList, as LinkedList creates an object (link) for each item in the queue.
I think you can some up with simple like implementation
package DataStructures;
public class Queue<T> {
private Node<T> root;
public Queue(T value) {
root = new Node<T>(value);
}
public void enque(T value) {
Node<T> node = new Node<T>(value);
node.setNext(root);
root = node;
}
public Node<T> deque() {
Node<T> node = root;
Node<T> previous = null;
while(node.next() != null) {
previous = node;
node = node.next();
}
node = previous.next();
previous.setNext(null);
return node;
}
static class Node<T> {
private T value;
private Node<T> next;
public Node (T value) {
this.value = value;
}
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setNext(Node<T> next) {
this.next = next;
}
public Node<T> next() {
return next;
}
}
}
However, if you still want to use the recursive algorithm, you can change it to be "tail-recursive" which probably is optimized in the JVM to avoid stack overflows.
O(1) access to first and last nodes.
class Queue {
private Node head;
private Node end;
public void enqueue(Integer data){
Node node = new Node(data);
if(this.end == null){
this.head = node;
this.end = this.head;
}
else {
this.end.setNext(node);
this.end = node;
}
}
public void dequeue (){
if (head == end){
end = null;
}
head = this.head.getNext();
}
#Override
public String toString() {
return head.getData().toString();
}
public String deepToString() {
StringBuilder res = new StringBuilder();
res.append(head.getData());
Node cur = head;
while (null != (cur = cur.getNext())){
res.append(" ");
res.append(cur.getData());
}
return res.toString();
}
}
class Node {
private Node next;
private Integer data;
Node(Integer i){
data = i;
}
public Integer getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Here is the Queue Implementation with Iterator and Iterable interface
Queue Size will increase as It gets full
Queue Interface
package com.practice.ds.queue;
import com.practice.ds.queue.exception.QueueException;
public interface QueueInterface<T> {
public boolean empty();
public void enqueue(T item);
public void dequeue() throws QueueException;
public T front() throws QueueException;
public void clear();
}
Custom Exception Class
package com.practice.ds.queue.exception;
public class QueueException extends Exception {
private static final long serialVersionUID = -884127093599336807L;
public QueueException() {
super();
}
public QueueException(String message) {
super(message);
}
public QueueException(Throwable e) {
super(e);
}
public QueueException(String message, Throwable e) {
super(message, e);
}
}
Implementation of Queue
package com.practice.ds.queue;
import java.util.Iterator;
import com.practice.ds.queue.exception.QueueException;
public class Queue<T> implements QueueInterface<T>, Iterable<T> {
private static final int DEFAULT_CAPACITY = 10;
private int current = 0;
private int rear = 0;
private T[] queueArray = null;
private int capacity = 0;
#SuppressWarnings("unchecked")
public Queue() {
capacity = DEFAULT_CAPACITY;
queueArray = (T[]) new Object[DEFAULT_CAPACITY];
rear = 0;
current = 0;
}
#Override
public boolean empty() {
return capacity == current;
}
#Override
public void enqueue(T item) {
if(full())
ensureCapacity();
queueArray[current] = item;
current++;
}
#Override
public void dequeue() throws QueueException {
T dequeuedItem = front();
rear++;
System.out.println("Dequed Item is " + dequeuedItem);
}
#Override
public T front() throws QueueException {
return queueArray[rear];
}
#Override
public void clear() {
for (int i = 0; i < capacity; i++)
queueArray[i] = null;
current = 0;
rear = 0;
}
#SuppressWarnings("unchecked")
private void ensureCapacity() {
if (rear != 0) {
copyElements(queueArray);
} else {
capacity *= 2;
T[] tempQueueArray = (T[]) new Object[capacity];
copyElements(tempQueueArray);
}
current -= rear;
rear = 0;
}
private void copyElements(T[] array) {
for (int i = rear; i < current; i++)
array[i - rear] = queueArray[i];
queueArray = array;
}
#Override
public Iterator<T> iterator() {
return new QueueItearator<T>();
}
public boolean full() {
return current == capacity;
}
private class QueueItearator<T> implements Iterator<T> {
private int index = rear;
#Override
public boolean hasNext() {
return index < current;
}
#SuppressWarnings("unchecked")
#Override
public T next() {
return (T) queueArray[index++];
}
}
}

Categories

Resources