Working With Stack - java

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.

Related

How to add an element in front of Queue in 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)

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.

Priority queue, Comparable

I have to write a priotity queye as implementation of the folowing interface:
public interface PQueue<T extends Comparable<T>> {
public void insert( T o ); // inserts o into the queue
public T remove(); // removes object with highest priority (by natural order)
}
I would be glad for some help and clues, becouse I don't even know how to begin with this issue.
I'd start off with something like this. The general idea is that you have an internal list and when you insert a new item you do a binary search to find where it belongs in that list. This way your internal list is always sorted so when you call remove() you just take the last (or first depending on how you're ordering things) item.
Disclaimer: This should be viewed as pseudo-code. I know for a fact there are problems with it. It's only intended to be a starting point.
public class PQueueImpl<T> implements PQueue<T> {
private List<T> internalQueue;
public void insert(T item){
int insertionPoint = Collections.binarySearch(internalQueue, item);
internalQueue.add(insertionPoint, item);
}
public T remove(){
return internalQueue.remove(internalQueue.size() - 1);
}
}
You could look at the source for java.util.PriorityQueue. Their implementation is backed by an Object array and is significantly more complex than the other example I gave, but I'm sure it works and performs much better too.
Priority queues are in practice implemented most commonly as heaps. They can also be implemented as a balanced binary search tree, or any other fast sorted data structure. The key is that the data structure must have very fast (faster than O(n)) max/min, insert, remove and update operations.

push in priorityqueue

I want to push some int to a priorityqueue but i can't! i used the queue.add() code but this code will return the sorted queue,please help,thank you!
A push/pop operation is clearly defined for a stack abstract data type; I'm not sure if it makes sense for a queue (or even a priority queue).
PriorityQueueimplementsQueue, which only specifies add/remove. On the other hand, a Deque has addFirst/Last, removeFirst/Last, etc. Perhaps one of these is what you're looking for.
An example
Here's an example of using a PriorityQueue of String, using a custom Comparator that compares lengths.
Queue<String> queue = new PriorityQueue<String>(
100, new Comparator<String>() {
#Override public int compare(String s1, String s2) {
return Integer.valueOf(s1.length()).compareTo(s2.length());
}
}
);
queue.add("Sally");
queue.add("Amy");
queue.add("Alice");
System.out.println(queue);
// "[Amy, Sally, Alice]"
System.out.println(queue.remove());
// "Amy"
System.out.println(queue.remove());
// "Alice"
queue.add("Tina");
System.out.println(queue.remove());
// "Tina"
As expected, the PriorityQueue will give the shortest String in the queue upon remove. Also as specified, ties are broken arbitrarily.
Related questions
On PriorityQueue
Java: How do I use a PriorityQueue?
In Java what should I use for a PriorityQueue that returns the greatest element first?
On Comparator and Comparable
When to use Comparable vs Comparator
Java: What is the difference between implementing Comparable and Comparator?
difference between compare() and compareTo()
Comparable and Comparator contract with regards to null
Why does the Java Collections Framework offer two different ways to sort?
The whole point of a priority queue is that it returns the smallest entry (or rather, the first element that'd appear in a sorted list) first. If that's not what you want, you probably don't want a straight PriorityQueue.
What you could do is create a class that has a PriorityQueue for the usual stuff, and a stack for "emergencies". Have a push(T) method that adds stuff to the stack, and an add(T) that adds to the queue. Whatever method gets the next element should remove it from the stack if there's anything there, else it gets the queue's next element.
I want to push some int to a
priorityqueue
'Push' is a stack operation, not a queue operation.
but i can't! i used the
queue.add() code but this code will
return the sorted queue
No it won't. A PriorityQueue is only sorted for the purposes of removing the head of the queue.
Your question doesn't make much sense. If you want to push, use a stack. If you don't want what a PriorityQueue does, don't use it.
What exactly is your actual problem?

How to pop items from a collection in Java?

Is there a method in JDK or apache commons to "pop" a list of elements from a java.util.List? I mean, remove the list of elements and return it, like this method:
public Collection pop(Collection elementsToPop, Collection elements) {
Collection popped = new ArrayList();
for (Object object : elementsToPop) {
if (elements.contains(object)) {
elements.remove(object);
popped.add(object);
}
}
return popped;
}
If you're looking for a stack-like structure I suggest accepting a Deque (LinkedList is the most common implementation) instead of a Collection.
If you don't actually need to treat it as a stack, just get an iterator from the Collection and use the remove() method:
for (Iterator<SomeType> it = elements.iterator(); it.hasNext(); ) {
SomeType e = it.next();
it.remove();
popped.add(e);
}
Do note that remove is an optional operation, and some implementations may throw an UnsupportedOperationException (for example, the iterator returned by a Collection from Collections.unmodifiable...() will).
Edit: After looking more closely at your question, I think you just need this:
elements.removeAll(elementsToRemove);
If your main point is you need to know exactly which elements were actually popped, I think you're stuck with your original code.
There is no such method in the standard JDK-provided methods. Apache Commons provides the ListUtils.subtract() method.
Edit: As other answerers have noted, your use of the term pop is nonstandard. Usually,
The pop operation removes an item from the top of [a stack]
Wikipedia has a nice description of stacks.
I guess no, because you definition of 'pop' operation is highly non-standard. Usually it takes no arguments (except collection itself) and returns and removes the top-most one.
But once you noted apache commons, this would achieve the same effect as your code.
Collection result = CollectionUtils.intersection(a, b);
a.removeAll(b);
edit
http://commons.apache.org/collections/api-release/index.html
Linked List provides the functionality as you require, provides a push and pop method.
Refer to the documentation as provided:
There isn't a method exactly like what you are asking for, but it looks like you are already pretty close with your code.
Some suggestions:
Consider using removeAll(object) instead of remove(object) if elements is an arbitrary collection since you may need to remove duplicates e.g. if elements is a list.
contains() is slow for some collection types (e.g. lists) since it needs to traverse the entire data structure. Given that this is in your inner loop you are at risk of O(n^2) performance issues. If you can make the algorithm work with a HashSet or HashMap then contains() will by O(1) and your algorithm will be much more efficient.

Categories