Java - sorted stack

I need a sorted stack. I mean, an element deleted from the stack should be with high priority. The size of the stack varies greatly (becomes very fast). I need to also look for items in this stack.

Is Java a good implementation for this? What class or algorithm do you propose for this?

I am using PriorityQueue right now, which I think is reasonable other than searching, so I wonder if I can use something better.

Thanks in advance!

Edit: I also need to delete the items! In conclusion: I need to maintain a sorted stack / queue, quickly get an item with high priority, and also quickly delete items

+3
source share
5 answers

TreeSet is a sorted collection. However, Set does not mean duplicates. add () adds an element that is inserted in the correct sorted place. pollLast () deletes and returns the last element, pollFirst () deletes and returns the first element.

+4
source

Java does not provide PriorityStack, but you can easily write one by wrapping the PriorityQueue class and providing push / pop methods to control the underlying queue.

+3
source

import java.util.Stack;

Q6_SortStack {

/**
 * @param args
 * Write a program to sort a stack in ascending order. 
 * You should not make any assumptions about how the stack is implemented. 
 * The following are the only functions that should be used to 
 * write this program: push | pop | peek | isEmpty.
 */
public static void main(String[] args) {
    int[] array = {2,5,10,3,11,7,13,8,9,4,1,6};
    Stack<Integer> s1 = new Stack<Integer>();
    //int[] array = {2,4,1,6};
    for(int i=0;i<array.length;i++){
        s1.push(array[i]);
    }
    //displayStack(s1);
    displayStack(sortStack(s1));
}
public static Stack<Integer> sortStack(Stack<Integer> s1){
    Stack<Integer> s2 = new Stack<Integer>();
    while(!s1.isEmpty()){
        int temp = s1.pop();
        while(!s2.isEmpty() && s2.peek()<temp){
            s1.push(s2.pop());
        }
        s2.push(temp);
    }
    return s2;
}
public static void displayStack(Stack<Integer> s){
    while(!s.isEmpty())
        System.out.print(s.pop()+"->");
    System.out.println("end");
}

}

+1

. . / , . , ( )

0

/ , , . , , , Arrays.sort(*Stack data array goes here*) java.util , .

0

Source: https://habr.com/ru/post/1742336/


All Articles