Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Last active January 2, 2016 21:39
Show Gist options
  • Save kanrourou/8365365 to your computer and use it in GitHub Desktop.
Save kanrourou/8365365 to your computer and use it in GitHub Desktop.
public class ResizingArrayStackOfStrings{
private String[] s;
private int N;
public ResizingArrayStackOfStrings(){
s=new String[1];
N=0;
}
public boolean isEmpty(){
return N==0;
}
public void push(String item){
if(N==s.length){
resize(2*s.length);
}
s[N++]=item;
}
public String pop(){
if(!isEmpty()){
String item=s[--N];
s[N]=null; //avoid loitering
if(N<=1/4*s.length){
resize(1/2*s.length);
}
return item;
}
else{
return "the stack is empty";
}
}
public void resize(int size){
String[] copy=new String[size];
for(int i=0;i<N;++i){
copy[i]=s[i];
}
s=copy;
}
public int length(){
return s.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment