How to add an element in front of Queue in java? - java

I am using Queue<T> q1 and I know that an element will be added using q1.offer(); at the end of the queue. But now, what I want to do is add an element in front of queue, which is not possible with Queue. The possible methods I could think of are
Use of double ended queue and I can add the elements in front and at the end.
reverse the q1, add the element at the end of the queue and reverse again.
Now, as a non-programmer guy, I am not sure, how to code these methods; which one is more economical and easier to do.
Problems I faced in 1) is transform of existing Queue to Deque and vice versa; and in 2) How to use Collections.reverseOrder(); to reverse the existing Queue.

The following is the way to add elements to the first of queue using deque and asLifoQueue method in collections.this will arrange the elements in last in first out order...
public class Practice15 {
public static void main(String[] args) {
Deque<Integer> dd=new ArrayDeque<Integer>();
dd.offerFirst(123);
dd.offerFirst(258);
dd.offerFirst(125);
System.out.println(dd);
Queue<Integer> q1=Collections.asLifoQueue(dd);
System.out.println(q1);
}
}

If you have to insert an element at the front, a Queue is definitely not the solution. Go for a double ended queue.

If you use "Queue q1" - that is only a declaration of variable q1, while Queue itself is only an interface. Are you probably looking to work with some implementation of Queue?
Check out Java API: http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html)

Related

Working With Stack

it has been to long since i asked here ..
I have this homework which has this Q Remove The Bottom Of The Stack I did it
good but not great ..
but now i have a Q is how to reverse the stack i did it by using another stack
is there a better way
this is what i did :
public static<T> void removeLast(LinkedList<T> st)
{
LinkedList<T> store = new LinkedList<>();
while (!st.eamty()){
store.push(st.pop());
}
store.pop();
while(!store.eamty()){
st.push(store.pop());
}
}
some src I found
Most efficient way to reverse a stack and add to an ArrayList
https://www.careercup.com/question?id=12689669
I'd made the following instead:
public static<T> void removeLast(LinkedList<T> st)
{
return st.removeLast();
}
But this is not a queue meant to be used and is also quite "expensive" operation ...
First of all, LinkedList<T> is not just a Stack. It is a List. In fact, it is a list class with a specific operation to removing the last element. (The removeLast method is defined by the Deque interface which LinkedList implements. The Deque abstraction is a "double ended queue"; i.e. something that can act as both a FIFO and a LIFO - a queue and a stack.)
So if you are able to the fact that this representation of a stack is implemented as a linked list, then the solution is to call that method.
On the other hand, if you are required / restricted to implementing your removeLast using only "stack-like" methods in the LinkedList API, then your approach of popping all elements to a temporary stack is probably as good as you can get.

Persistent Queue datastructure

I need to make a class Persistent queue in which the function enqueue takes an element enqueues it to the current queue and return the new queue. How ever the original queue remains unchanged. Similarly the dequeue function removes the front element an returns the new queue but the original queue remains unchanged. This can of course be done in O(length of queue) but can i do it faster.??
You can use a linked list as queue (not LinkedList, but your own implementation).
To add a new element you only have to create a new instance of your queue class, set its start element to the copied queue's start element, and create a new end element.
Removing an element is similar, but set the end element of the new queue to the second to last element of the copied queue.
The queue class could look like this:
static class Node {
final Node next;
final Object o;
Node(Node next, Object o) {...}
}
final Node start, end;
private Queue(Node start, Node end) {...}
public Queue(Object o) {
start = end = new Node(null, o);
}
public Queue add(Object o) {
return new Queue(start, new Node(end, o));
}
public Queue remove() {
return new Queue(start, end.next);
}
The complexity of this queue's add and remove methods is O(1).
Please note that you can only iterate this queue in reverse order (i.e. newest elements first). Maybe you can come up with something that can be iterated the other way around or even in both directions.
I suggest to have a look to scala implementation. Comment at the top of the class describes the chosen approach (complexity : O(1)).
Queue is implemented as a pair of Lists, one containing the ''in'' elements and the other the ''out'' elements.
Elements are added to the ''in'' list and removed from the ''out'' list. When the ''out'' list runs dry, the
queue is pivoted by replacing the ''out'' list by ''in.reverse'', and ''in'' by ''Nil''.
Adding items to the queue always has cost O(1). Removing items has cost O(1), except in the case
where a pivot is required, in which case, a cost of O(n) is incurred, where n is the number of elements in the queue. When this happens,
n remove operations with O(1) cost are guaranteed. Removing an item is on average O(1).
http://xuwei-k.github.io/scala-library-sxr/scala-library-2.10.0/scala/collection/immutable/Queue.scala.html
What I do is use Java Chronicle (disclaimer: which I wrote). This is an unbounded off heap persisted queue which is stored on disk or tmpfs (shared memory).
In this approach your consumer keeps track of where it is up to in the queue, but no entry is actually removed (except in a daily or weekly maintenance cycle)
This avoids the need to alter the queue except when adding to it, and you would not need to copy it.
As such maintaining multiple references to where each consumer believes is the tail of the queue is O(1) for each consumer.
As Chronicle uses a compact binary form, the limit to how much you can store is limited by your disk space. e.g. a 2 TB drive can store this much data even on a machine with 8 GB before you have to rotate the queue logs.

what is a more efficient way to implement enqueue in Java

So I have this simple code in java. It enqueue (adds) and element to the end of the queue (implemented by an ArrayList) without changing the original queue. The code:
public class MyQueue<T>{
private List<T> body;
// some constructors and helper functions.
//copy constructor
public Queue(List<T> list){
this.body = list;
}
//this is the function
public MyQueue<T> enqueue(T obj){
List<T> temp = new ArrayList<T>(body);
temp.add(obj);
return new Queue<T>(temp);
}
The whole Idea is to make enqueue faster and more efficient, and again, as you notice, without changing the value of the original queue.
UPDATE For the sake of completing the idea.
1- This is an assignment so university, the skeleton provided is not to be changed, the task is to make the function enqueue faster (i do realize i am copying twice and thats the slow part).
2- As for the helper functions, they are simple:
public T peek(){
if(body.isEmpty()){
thrown new NoSuchElementException();
}
return body.get(0);
}
public int size(){
return body.size();
}
Any ideas? thanks
A queue is a basic data structure and it's hard to make it better than the experts having worked on it. The simplest and fastest general purpose implementation is probably the ArrayDeque and there's hardly anything to improve.
What you're doing is strange at best:
Instead of appending an element, you copy the whole content. Why?
You insert the new element at the highest index, why? This way your poll (dequeue, remove, whatever) must remove the index at element 0, which is slow for ArrayList.
Actually, I have no idea how your poll may look like. In any case, your enqueue doesn't do what I'd expect from a method called like this.
Use a LinkedList instead of an ArrayList. You don't need indexed access in a queue, but you do need fast enqueue/dequeue. If you need indexed access. It isn't really a queue at all. And just use the add() method, don't create a whole new queue every time. Your enqueue() method should return 'this', or void. And don't allow the caller to supply the list: create your own.

Queue using 2 stacks, deletion in O(1)

I have implemented a Queue using 2 Stacks in Java where I follow this algorithm:
enQueue(x)
Push x to stack1
deQueue()
1) If both stacks are empty then error.
2) If stack2 is empty while stack1 is not empty, push everything from stack1 to stack2.
3) Pop the element from stack2 and return it.
Now, the problem here is that the first deQueue() operation is very slow (since it transfers everything to stack2). Can we modify the algorithm somehow so that deQueue is O(1) always? Are there other alternatives?
You can swap the two stacks.
deQueue()
If both stacks are empty then error.
If stack2 is empty, while
stack1 is not empty, swap the two stacks.
Pop the element from
stack2 and return it.
Using a swap, the operation is always O(1)
If you need a FIFO queue, use two queues. Only use a stack if you need LIFO behaviour.
If this is the case, there is no difference between using one queue or two queues, so you may as well use just one queue. If you are using threads, use an ExecutorService which wraps a Queue and a thread pool.
I'll bite: Why not use a doubly linked list? This should be O(1) push and O(1) pop.
When we say first deQueue() operation is very slow (since it transfers everything to stack2).
I am assuming we are talking about this
2) If stack2 is empty while stack1 is not empty, push everything from
stack1 to stack2.
Are we simply transferring everything we have in stack1 to stack2, in same order. That will be simple assignment (stack2=stack1;) and hence O(1).
Alternatively, if we are saying we need to pop everything from stack1, one by one, and add to stack2. We are basically talking about reversing a list(stack1), and assigning to stack2 (assignment is O(1), we know). There are various good algorithms to reverse a list http://www.codeproject.com/Articles/27742/How-To-Reverse-a-Linked-List-3-Different-Ways.
If you are using Java(as per the tag), you could simple use Collections.reverse(arrayList); to reverse the list.

FIFO based Queue implementations?

I need a simple FIFO implemented queue for storing a bunch of ints (I don't mind much if it is generics implementation).
Anything already baked for me in java.util or Trove/Guava library?
Yeah. Queue
LinkedList being the most trivial concrete implementation.
Here is example code for usage of java's built-in FIFO queue:
public static void main(String[] args) {
Queue<Integer> myQ = new LinkedList<Integer>();
myQ.add(1);
myQ.add(6);
myQ.add(3);
System.out.println(myQ); // 1 6 3
int first = myQ.poll(); // retrieve and remove the first element
System.out.println(first); // 1
System.out.println(myQ); // 6 3
}
ArrayDeque is probably the fastest object-based queue in the JDK; Trove has the TIntQueue interface, but I don't know where its implementations live.
A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :
#Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
1
2
Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.
So this is a Queue only if used in conjunction with add.
Try this :
#Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.push(1);
queue.push(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
2
1
Queue is an interface that extends Collection in Java. It has all the functions needed to support FIFO architecture.
For concrete implementation you may use LinkedList. LinkedList implements Deque which in turn implements Queue. All of these are a part of java.util package.
For details about method with sample example you can refer FIFO based Queue implementation in Java.
PS: Above link goes to my personal blog that has additional details on this.

Categories