Created
December 18, 2017 11:10
-
-
Save skmangalam/3dcfc82752b2a6a8cfb0a77554c03316 to your computer and use it in GitHub Desktop.
Implementation of Stack Class using Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BasicStack<X> implements Stack<X>{ | |
private X[] data; | |
private int stackPointer; | |
public BasicStack(){ | |
data = (X[])new Object[1000]; | |
stackPointer = 0; | |
} | |
public void push(X newItem){ | |
data[stackPointer++] = newItem; | |
//stackPointer++; | |
} | |
public X pop(){ | |
if(stackPointer==0) | |
throw new IllegalStateException("No more items on the stack"); | |
//--stackPointer; | |
return data[--stackPointer]; | |
} | |
public boolean contains(X item){ | |
boolean found = false; | |
for(int i=0;i<stackPointer;i++){ | |
if(data[i].equals(item)) | |
{ | |
found = true; | |
return found; | |
} | |
} | |
return found; | |
} | |
public X access(X item){ | |
while(stackPointer > 0){ | |
X tmpItem = pop(); | |
if(item.equals(tmpItem)) | |
return tmpItem; | |
} | |
throw new IllegalArgumentException("Could not find "+item +"on the stack"); | |
} | |
public int size(){ | |
return stackPointer; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment