Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitcpf/ae426595e81cfcc832a8 to your computer and use it in GitHub Desktop.
Save bitcpf/ae426595e81cfcc832a8 to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class PeakStack {
Stack<Integer> origin;
Stack<Integer> peak;
int top_o;
int top_p;
public PeakStack(){
origin = new Stack();
peak = new Stack();
top_o = -100000;
top_p = -100000;
}
public void push(Integer item){
if(item >= top_p || (peak.empty() && origin.empty())){
origin.push(item);
peak.push(item);
top_p = item;
return;
}
if(item < top_p){
int cnt = 0;
int temp = (int) peak.pop();
while(temp > item && !peak.empty()){
origin.push(temp);
cnt ++;
temp = (int) peak.pop();
}
peak.push(temp > item?temp:item);
peak.push(item > temp?item:temp);
while(cnt > 0){
peak.push(origin.pop());
cnt --;
}
origin.push(item);
}
}
public int pop(){
int temp = origin.pop();
int cnt = 0;
int p_temp = peak.pop();
while(temp != p_temp){
origin.push(p_temp);
cnt ++;
p_temp = peak.pop();
}
while(cnt > 0 ){
peak.push(origin.pop());
cnt --;
}
return temp;
}
public int peakpop(){
int p_temp = peak.pop();
int cnt = 0;
int temp = origin.pop();
while(temp != p_temp){
peak.push(temp);
cnt ++;
temp = origin.pop();
}
while(cnt > 0 ){
origin.push(peak.pop());
cnt --;
}
return p_temp;
}
public static void main(String[] args){
PeakStack test = new PeakStack();
test.push(2);
test.push(1);
test.push(5);
test.push(7);
test.push(4);
System.out.println(test.pop());
System.out.println(test.pop());
System.out.println(test.peakpop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment