This is a data structure that supports the push(), pop() and isEmpty() operations and returns the least element on every pop(). In a sense this works like a PriorityQueue only in O(n) runtime against the O(log n) runtime of a PriorityQueue.
This is my implementation,
public class SortedStack<T extends Comparable<T>> {
private int size;
private Stack<T> s1;
private Stack<T> s2;
public SortedStack(){
s1 = new Stack<>();
s2 = new Stack<>();
size = 0;
}
public int compareTo(T other){
return compareTo(other);
}
public void push(T item){
size++;
if(s1.getHead() == null){
s1.push(item);
return;
}
while(!s1.isEmpty()){
if(s1.peek().compareTo(item) < 0){
s2.push(s1.pop());
}else if((s1.peek().compareTo(item) > 0) || (s1.peek().compareTo(item) == 0)){
s1.push(item);
break;
}
}
while(!s2.isEmpty()){
s1.push(s2.pop());
}
}
public T pop(){
size--;
return s1.pop();
}
public boolean isEmpty(){
return size == 0;
}
}
The Stack implementation that it uses is as follows:
public class Stack<T>{
private Node head;
private class Node<T>{
private T data;
private Node next;
public Node(T data){
this.data = data;
next = null;
}
}
public Node getHead(){
return head;
}
public void push(T item){
Node p = new Node((Comparable) item);
if(head == null){
head = p;
return;
}
p.next = head;
head = p;
}
public T pop(){
if(head == null){
System.out.println("Popping off an empty stack!!!");
System.exit(-1);
}
T item = (T) head.data;
head = head.next;
return item;
}
public T peek(){
if(head == null){
System.out.println("Empty Stack!!");
System.exit(-1);
}
return (T) head.data;
}
public boolean isEmpty(){
return head == null;
}
}
Invite reviews.