Created
June 22, 2018 21:00
-
-
Save Juliet-Selebalo/d4b754e714f702b06fe50c0d00c7c25f to your computer and use it in GitHub Desktop.
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
package stack; | |
import java.util.Arrays; | |
/** | |
* | |
* @author Student | |
* @param <T> | |
*/ | |
public class StackImpl <T>implements Stack<T>{ | |
T[] stack; | |
int capacity; | |
int top; | |
int size; | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
// TODO code application logic here | |
} | |
public StackImpl(int capacity){ | |
stack = (T[]) new Object[capacity]; | |
this.capacity = capacity; | |
this.top = -1; | |
} | |
@Override | |
public boolean isFull(){ | |
return capacity == size; | |
} | |
@Override | |
public boolean isEmpty(){ | |
return top==-1; | |
} | |
@Override | |
public void push (T t){ | |
this.top = top++; | |
if(!isFull()){ | |
stack[top]=t; | |
} | |
else{ | |
this.expand(); | |
this.push(t); | |
} | |
size++; | |
} | |
@Override | |
public T peek(){ | |
return this.stack[top]; | |
} | |
@Override | |
public T pop(){ | |
T temp = this.stack[top]; | |
if(!isEmpty()){ | |
stack[top]= null; | |
} | |
this.top = top--; | |
size = size--; | |
return temp; | |
} | |
private void expand() { | |
this.capacity = this.capacity*2; | |
T[] newStack = (T[]) new Object[this.capacity]; | |
System.arraycopy(this.stack, 0, newStack, 0, this.stack.length); | |
this.stack = newStack; | |
//this.stack = Arrays.copyOf(stack, capacity); | |
/*T[] newStack = (T[]) new Object[this.capacity]; | |
for (int i = 0; i < this.stack.length; i++) { | |
newStack[i] = this.stack[i]; | |
} | |
this.stack = newStack;*/ | |
} | |
@Override | |
public int search(T t){ | |
for(int i = 0; i<this.stack.length; i++){ | |
if(t==this.stack[i]){ | |
return i; | |
} | |
} | |
return -1; | |
} | |
} |
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
package stack; | |
/** | |
* | |
* @author Student | |
* @param <T> | |
*/ | |
public interface Stack <T> { | |
T pop(); | |
void push(T t); | |
T peek(); | |
int search(T t); | |
boolean isEmpty(); | |
boolean isFull(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment