Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Created July 1, 2014 14:18
Show Gist options
  • Save bitcpf/34c6d76cf8dd6a15e17e to your computer and use it in GitHub Desktop.
Save bitcpf/34c6d76cf8dd6a15e17e to your computer and use it in GitHub Desktop.
package cc150_3_1;
public class ArrayStack {
private int[] data;
private int[] sk_lp = new int[3];
private int[] sk_hp = new int[3];
private int[] top_p = new int[3];
public ArrayStack(int capacity) throws Exception{
if(capacity < 3) {
throw new Exception("Must larger than 3");
}
data = new int[capacity];
SetPointer(capacity);
}
private void SetPointer(int capacity){
int gap = capacity/3;
for(int i=0;i<3;i++){
sk_lp[i] = gap*i;
top_p[i] = sk_lp[i];
sk_hp[i] = gap*(i+1);
}
}
public void push(int val, int stackID) throws Exception{
if(stackID < 0 || stackID>=3){
throw new Exception("Wrong Stack");
}
int top = top_p[stackID];
int high = sk_hp[stackID];
if(top == high){
throw new Exception("Stack Overflow");
}
data[top] = val;
top_p[stackID]++;
}
public int pop(int stackID) throws Exception{
if(stackID < 0 || stackID>=3){
throw new Exception("Wrong Stack");
}
int top = top_p[stackID];
int low = sk_hp[stackID];
if(top == low){
throw new Exception("Stack already empty");
}
int temp = data[top];
top_p[stackID] --;
return temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment